-
Notifications
You must be signed in to change notification settings - Fork 113
feat(insights): add OpenAI provider for transcription and translation #848
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
xynstr
wants to merge
2
commits into
mynaparrot:main
Choose a base branch
from
xynstr:feat/openai-provider
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.
+1,050
−1
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| // Package openai implements insights.Provider against the OpenAI API and any | ||
| // OpenAI-compatible HTTP backend (LocalAI, vLLM, llama.cpp-server, whisper.cpp, | ||
| // etc.). The base_url provider option lets operators point this provider at a | ||
| // self-hosted endpoint while keeping the same Go code path as for OpenAI cloud. | ||
| package openai | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
|
|
||
| openaisdk "github.com/openai/openai-go/v3" | ||
| "github.com/openai/openai-go/v3/option" | ||
|
|
||
| "github.com/mynaparrot/plugnmeet-protocol/plugnmeet" | ||
| "github.com/mynaparrot/plugnmeet-server/pkg/config" | ||
| "github.com/mynaparrot/plugnmeet-server/pkg/insights" | ||
| "github.com/sirupsen/logrus" | ||
| ) | ||
|
|
||
| const ( | ||
| defaultTranscriptionModel = "whisper-1" | ||
| defaultChatModel = "gpt-4o-mini" | ||
| defaultChunkSeconds = 5.0 | ||
| transcriptionSampleRate = 16000 | ||
| ) | ||
|
|
||
| // Provider implements insights.Provider for OpenAI and OpenAI-compatible APIs. | ||
| type Provider struct { | ||
| account *config.ProviderAccount | ||
| service *config.ServiceConfig | ||
| client openaisdk.Client | ||
| logger *logrus.Entry | ||
| } | ||
|
|
||
| // NewProvider builds a Provider. The api_key credential is required; the | ||
| // base_url option is optional and overrides the SDK's default endpoint. | ||
| func NewProvider(providerAccount *config.ProviderAccount, serviceConfig *config.ServiceConfig, log *logrus.Entry) (insights.Provider, error) { | ||
| if providerAccount == nil { | ||
| return nil, fmt.Errorf("openai: provider account is nil") | ||
| } | ||
| if providerAccount.Credentials.APIKey == "" { | ||
| return nil, fmt.Errorf("openai: credentials.api_key is required") | ||
| } | ||
|
|
||
| opts := []option.RequestOption{ | ||
| option.WithAPIKey(providerAccount.Credentials.APIKey), | ||
| } | ||
| if baseURL, _ := providerAccount.Options["base_url"].(string); baseURL != "" { | ||
| opts = append(opts, option.WithBaseURL(baseURL)) | ||
| } | ||
|
|
||
| return &Provider{ | ||
| account: providerAccount, | ||
| service: serviceConfig, | ||
| client: openaisdk.NewClient(opts...), | ||
| logger: log.WithField("service", "openai"), | ||
| }, nil | ||
| } | ||
|
|
||
| // CreateTranscription opens a chunked transcription stream that periodically | ||
| // uploads buffered PCM16 audio to /v1/audio/transcriptions and emits a | ||
| // final_result event per chunk. | ||
| func (p *Provider) CreateTranscription(ctx context.Context, roomId, userId string, options []byte) (insights.TranscriptionStream, error) { | ||
| opts := &insights.TranscriptionOptions{} | ||
| if len(options) > 0 { | ||
| if err := json.Unmarshal(options, opts); err != nil { | ||
| return nil, fmt.Errorf("openai: failed to unmarshal transcription options: %w", err) | ||
| } | ||
| } | ||
|
|
||
| model := p.serviceModel(defaultTranscriptionModel) | ||
| chunkSec := p.chunkSeconds() | ||
|
|
||
| return newChunkedStream(ctx, p.client, model, chunkSec, roomId, userId, opts, p.logger) | ||
| } | ||
|
|
||
| // TranslateText performs translation via Chat Completions with a JSON-schema | ||
| // constrained response. One round-trip handles all target languages. | ||
| func (p *Provider) TranslateText(ctx context.Context, text, sourceLang string, targetLangs []string) (*plugnmeet.InsightsTextTranslationResult, error) { | ||
| if len(targetLangs) == 0 { | ||
| return nil, fmt.Errorf("openai: at least one target language is required") | ||
| } | ||
| model := p.serviceModel(defaultChatModel) | ||
| return translateViaChatCompletions(ctx, p.client, model, text, sourceLang, targetLangs, p.logger) | ||
| } | ||
|
|
||
| // SynthesizeText is intentionally not implemented: TTS via the OpenAI audio | ||
| // endpoint can be added in a follow-up; until then we surface a clear error. | ||
| func (p *Provider) SynthesizeText(_ context.Context, _ []byte) (io.ReadCloser, error) { | ||
| return nil, fmt.Errorf("openai: speech synthesis not implemented") | ||
| } | ||
|
|
||
| // GetSupportedLanguages returns the static language lists for transcription | ||
| // and translation. Whisper / OpenAI translation models support far more codes | ||
| // than this list; we surface only the subset we exercise in PlugNmeet. | ||
| func (p *Provider) GetSupportedLanguages(serviceType insights.ServiceType) []*plugnmeet.InsightsSupportedLangInfo { | ||
| if langs, ok := supportedLanguages[serviceType]; ok { | ||
| out := make([]*plugnmeet.InsightsSupportedLangInfo, len(langs)) | ||
| for i := range langs { | ||
| out[i] = &langs[i] | ||
| } | ||
| return out | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // AITextChatStream is not supported by this provider in its current scope. | ||
| func (p *Provider) AITextChatStream(_ context.Context, _ string, _ []*plugnmeet.InsightsAITextChatContent) (<-chan *plugnmeet.InsightsAITextChatStreamResult, error) { | ||
| return nil, nil | ||
| } | ||
|
|
||
| // AIChatTextSummarize is not supported by this provider in its current scope. | ||
| func (p *Provider) AIChatTextSummarize(_ context.Context, _ string, _ []*plugnmeet.InsightsAITextChatContent) (string, uint32, uint32, error) { | ||
| return "", 0, 0, nil | ||
| } | ||
|
|
||
| // StartBatchSummarizeAudioFile is not supported by this provider. | ||
| func (p *Provider) StartBatchSummarizeAudioFile(_ context.Context, _, _, _ string) (string, string, error) { | ||
| return "", "", nil | ||
| } | ||
|
|
||
| // CheckBatchJobStatus is not supported by this provider. | ||
| func (p *Provider) CheckBatchJobStatus(_ context.Context, _ string) (*insights.BatchJobResponse, error) { | ||
| return nil, nil | ||
| } | ||
|
|
||
| // DeleteUploadedFile is not supported by this provider. | ||
| func (p *Provider) DeleteUploadedFile(_ context.Context, _ string) error { | ||
| return nil | ||
| } | ||
|
|
||
| // serviceModel reads the per-service model name from the service config, | ||
| // falling back to the supplied default. The provider account can also pin a | ||
| // model via its own options as a coarse default for both services. | ||
| func (p *Provider) serviceModel(fallback string) string { | ||
| if p.service != nil { | ||
| if m, _ := p.service.Options["model"].(string); m != "" { | ||
| return m | ||
| } | ||
| } | ||
| if p.account != nil { | ||
| if m, _ := p.account.Options["model"].(string); m != "" { | ||
| return m | ||
| } | ||
| } | ||
| return fallback | ||
| } | ||
|
|
||
| // chunkSeconds reads chunk_seconds from the provider account options. YAML | ||
| // numbers arrive as float64 from gopkg.in/yaml.v3; ints are accepted too. | ||
| func (p *Provider) chunkSeconds() float64 { | ||
| if p.account == nil { | ||
| return defaultChunkSeconds | ||
| } | ||
| switch v := p.account.Options["chunk_seconds"].(type) { | ||
| case float64: | ||
| if v > 0 { | ||
| return v | ||
| } | ||
| case int: | ||
| if v > 0 { | ||
| return float64(v) | ||
| } | ||
| } | ||
| return defaultChunkSeconds | ||
| } |
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,79 @@ | ||
| package openai | ||
|
|
||
| import ( | ||
| "github.com/mynaparrot/plugnmeet-protocol/plugnmeet" | ||
| "github.com/mynaparrot/plugnmeet-server/pkg/insights" | ||
| ) | ||
|
|
||
| // supportedLanguages enumerates the languages we surface for transcription | ||
| // and translation. The transcription set tracks Whisper's documented | ||
| // coverage; the translation set is the same superset since modern chat | ||
| // models (gpt-4o, gpt-4o-mini, Llama-class instruct models) translate | ||
| // between any of these pairs comfortably. | ||
| var supportedLanguages = map[insights.ServiceType][]plugnmeet.InsightsSupportedLangInfo{ | ||
| insights.ServiceTypeTranscription: whisperLanguages(), | ||
| insights.ServiceTypeTranslation: whisperLanguages(), | ||
| } | ||
|
|
||
| func whisperLanguages() []plugnmeet.InsightsSupportedLangInfo { | ||
| return []plugnmeet.InsightsSupportedLangInfo{ | ||
| {Code: "af", Name: "Afrikaans", Locale: "af"}, | ||
| {Code: "ar", Name: "Arabic", Locale: "ar"}, | ||
| {Code: "az", Name: "Azerbaijani", Locale: "az"}, | ||
| {Code: "be", Name: "Belarusian", Locale: "be"}, | ||
| {Code: "bg", Name: "Bulgarian", Locale: "bg"}, | ||
| {Code: "bn", Name: "Bengali", Locale: "bn"}, | ||
| {Code: "bs", Name: "Bosnian", Locale: "bs"}, | ||
| {Code: "ca", Name: "Catalan", Locale: "ca"}, | ||
| {Code: "cs", Name: "Czech", Locale: "cs"}, | ||
| {Code: "cy", Name: "Welsh", Locale: "cy"}, | ||
| {Code: "da", Name: "Danish", Locale: "da"}, | ||
| {Code: "de", Name: "German", Locale: "de"}, | ||
| {Code: "el", Name: "Greek", Locale: "el"}, | ||
| {Code: "en", Name: "English", Locale: "en"}, | ||
| {Code: "es", Name: "Spanish", Locale: "es"}, | ||
| {Code: "et", Name: "Estonian", Locale: "et"}, | ||
| {Code: "fa", Name: "Persian", Locale: "fa"}, | ||
| {Code: "fi", Name: "Finnish", Locale: "fi"}, | ||
| {Code: "fr", Name: "French", Locale: "fr"}, | ||
| {Code: "gl", Name: "Galician", Locale: "gl"}, | ||
| {Code: "he", Name: "Hebrew", Locale: "he"}, | ||
| {Code: "hi", Name: "Hindi", Locale: "hi"}, | ||
| {Code: "hr", Name: "Croatian", Locale: "hr"}, | ||
| {Code: "hu", Name: "Hungarian", Locale: "hu"}, | ||
| {Code: "hy", Name: "Armenian", Locale: "hy"}, | ||
| {Code: "id", Name: "Indonesian", Locale: "id"}, | ||
| {Code: "is", Name: "Icelandic", Locale: "is"}, | ||
| {Code: "it", Name: "Italian", Locale: "it"}, | ||
| {Code: "ja", Name: "Japanese", Locale: "ja"}, | ||
| {Code: "kk", Name: "Kazakh", Locale: "kk"}, | ||
| {Code: "kn", Name: "Kannada", Locale: "kn"}, | ||
| {Code: "ko", Name: "Korean", Locale: "ko"}, | ||
| {Code: "lt", Name: "Lithuanian", Locale: "lt"}, | ||
| {Code: "lv", Name: "Latvian", Locale: "lv"}, | ||
| {Code: "mi", Name: "Maori", Locale: "mi"}, | ||
| {Code: "mk", Name: "Macedonian", Locale: "mk"}, | ||
| {Code: "mr", Name: "Marathi", Locale: "mr"}, | ||
| {Code: "ms", Name: "Malay", Locale: "ms"}, | ||
| {Code: "ne", Name: "Nepali", Locale: "ne"}, | ||
| {Code: "nl", Name: "Dutch", Locale: "nl"}, | ||
| {Code: "no", Name: "Norwegian", Locale: "no"}, | ||
| {Code: "pl", Name: "Polish", Locale: "pl"}, | ||
| {Code: "pt", Name: "Portuguese", Locale: "pt"}, | ||
| {Code: "ro", Name: "Romanian", Locale: "ro"}, | ||
| {Code: "ru", Name: "Russian", Locale: "ru"}, | ||
| {Code: "sk", Name: "Slovak", Locale: "sk"}, | ||
| {Code: "sl", Name: "Slovenian", Locale: "sl"}, | ||
| {Code: "sr", Name: "Serbian", Locale: "sr"}, | ||
| {Code: "sv", Name: "Swedish", Locale: "sv"}, | ||
| {Code: "sw", Name: "Swahili", Locale: "sw"}, | ||
| {Code: "ta", Name: "Tamil", Locale: "ta"}, | ||
| {Code: "th", Name: "Thai", Locale: "th"}, | ||
| {Code: "tl", Name: "Tagalog", Locale: "tl"}, | ||
| {Code: "tr", Name: "Turkish", Locale: "tr"}, | ||
| {Code: "uk", Name: "Ukrainian", Locale: "uk"}, | ||
| {Code: "ur", Name: "Urdu", Locale: "ur"}, | ||
| {Code: "vi", Name: "Vietnamese", Locale: "vi"}, | ||
| {Code: "zh", Name: "Chinese", Locale: "zh"}, | ||
| } | ||
| } | ||
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.
To improve efficiency and avoid allocating two identical slices, you can define the list of languages as a single package-level variable and reuse it in the
supportedLanguagesmap. This also makes the code slightly more readable by removing thewhisperLanguages()function.