Repository navigation
Go: implement rerank, asr, tts for TogetherAI - #15107
Conversation
📝 WalkthroughWalkthroughThis PR extends TogetherAI provider support by implementing four API method stubs: ChangesTogetherAI Provider Method Implementation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@conf/models/togetherai.json`:
- Around line 58-64: The max_tokens value for the model entry with "name":
"mixedbread-ai/mxbai-rerank-large-v2" is a string ("16384"); change it to an
integer (16384) so the "max_tokens" field is numeric and consistent with other
entries (remove the surrounding quotes from the "max_tokens" value).
In `@internal/entity/models/togetherai.go`:
- Around line 682-741: The AudioSpeech method dereferences *modelName without
validating it and uses http.NewRequest without a request context; update
TogetherAIModel.AudioSpeech to validate modelName (nil and empty check like
Embed/ChatWithMessages) before using it, and create the POST request with a
context deadline by wrapping a context.WithTimeout(context.Background(),
nonStreamCallTimeout) and calling http.NewRequestWithContext so the request
honors the shared nonStreamCallTimeout and matches the rest of the file.
- Around line 497-570: The Rerank method has multiple nil-dereference and logic
issues: guard against nil rerankConfig before accessing TopN and replace the
redundant topN assignment with a single defaulting expression (use a default
value when rerankConfig is nil or TopN==0), validate modelName is
non-nil/non-empty before using *modelName (same validation as Embed), require
apiConfig and apiConfig.ApiKey to be non-nil and return a clear error if missing
before building the Authorization header, replace direct t.BaseURL[region] usage
with baseURLForRegion(region) to ensure a valid base URL or return an error if
missing, and create the request with a context deadline (use context.WithTimeout
and nonStreamCallTimeout, then http.NewRequestWithContext) rather than bare
http.NewRequest to avoid indefinite hangs; update references in this function
(Rerank, rerankConfig, modelName, apiConfig, baseURLForRegion,
nonStreamCallTimeout) accordingly.
- Around line 576-676: The TranscribeAudio function never sends the required
multipart "model" field (so modelName is unused) and it uses http.NewRequest so
request contexts/timeouts aren't honored; update TranscribeAudio to accept a ctx
context.Context parameter, use writer.WriteField("model", *modelName) when
modelName != nil && *modelName != "" (before writer.Close()), and create the
HTTP request with http.NewRequestWithContext(ctx, "POST", url, &body) so
t.httpClient.Do honors cancellation/timeouts; update all call sites of
TranscribeAudio to pass the caller's context.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 13a16202-be1f-4ea3-9a64-3176b20a4777
📒 Files selected for processing (2)
conf/models/togetherai.jsoninternal/entity/models/togetherai.go
| { | ||
| "name": "mixedbread-ai/mxbai-rerank-large-v2", | ||
| "max_tokens": "16384", | ||
| "model_types": [ | ||
| "rerank" | ||
| ] | ||
| }, |
There was a problem hiding this comment.
max_tokens must be an integer, not a string.
Every other model entry in this file declares max_tokens as an integer (e.g., 131072, 512, 262144). Quoting "16384" here introduces a type inconsistency that will fail to unmarshal if the consumer expects a numeric type, and at minimum is a latent footgun for downstream code.
🔧 Proposed fix
{
"name": "mixedbread-ai/mxbai-rerank-large-v2",
- "max_tokens": "16384",
+ "max_tokens": 16384,
"model_types": [
"rerank"
]
},📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| { | |
| "name": "mixedbread-ai/mxbai-rerank-large-v2", | |
| "max_tokens": "16384", | |
| "model_types": [ | |
| "rerank" | |
| ] | |
| }, | |
| { | |
| "name": "mixedbread-ai/mxbai-rerank-large-v2", | |
| "max_tokens": 16384, | |
| "model_types": [ | |
| "rerank" | |
| ] | |
| }, |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@conf/models/togetherai.json` around lines 58 - 64, The max_tokens value for
the model entry with "name": "mixedbread-ai/mxbai-rerank-large-v2" is a string
("16384"); change it to an integer (16384) so the "max_tokens" field is numeric
and consistent with other entries (remove the surrounding quotes from the
"max_tokens" value).
| func (t *TogetherAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", t.Name()) | ||
| if len(documents) == 0 { | ||
| return &RerankResponse{}, nil | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", t.BaseURL[region], t.URLSuffix.Rerank) | ||
|
|
||
| var topN = rerankConfig.TopN | ||
| if rerankConfig.TopN != 0 { | ||
| topN = rerankConfig.TopN | ||
| } | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, | ||
| "query": query, | ||
| "documents": documents, | ||
| "top_n": topN, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
||
| resp, err := t.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("TogetherAI Rerank API error: status %d, body: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| var rerankResp struct { | ||
| Results []struct { | ||
| Index int `json:"index"` | ||
| RelevanceScore float64 `json:"relevance_score"` | ||
| } `json:"results"` | ||
| } | ||
|
|
||
| if err = json.Unmarshal(body, &rerankResp); err != nil { | ||
| return nil, fmt.Errorf("failed to decode response: %w", err) | ||
| } | ||
|
|
||
| var rerankResponse RerankResponse | ||
| for _, result := range rerankResp.Results { | ||
| rerankResult := RerankResult{ | ||
| Index: result.Index, | ||
| RelevanceScore: result.RelevanceScore, | ||
| } | ||
| rerankResponse.Data = append(rerankResponse.Data, rerankResult) | ||
| } | ||
|
|
||
| return &rerankResponse, nil | ||
| } |
There was a problem hiding this comment.
Multiple nil-dereference panics + dead branch in Rerank.
Several runtime panics are reachable here, plus a redundant block:
- Line 509 —
rerankConfig.TopNwill panic ifrerankConfigisnil. The method signature accepts*RerankConfigbut the code never checks it. - Line 515 —
*modelNamewill panic ifmodelNameisnilor empty (no validation, unlikeEmbedat lines 414-416). - Line 532 —
*apiConfig.ApiKeywill panic ifapiConfigisnilorapiConfig.ApiKeyisnil. The earlier check at line 503 only guardsapiConfigfor region lookup, not for the auth header. - Line 509-512 —
var topN = rerankConfig.TopN; if rerankConfig.TopN != 0 { topN = rerankConfig.TopN }— both branches assign the same value; theifis dead code. - Line 507 — bypasses
baseURLForRegion(region)(used everywhere else in the file), so a missing/empty base URL silently produces a malformed URL instead of a clear error. - Line 526 — uses bare
http.NewRequestwith no context/deadline. The sharedhttpClientonly setstransport.ResponseHeaderTimeout, not an overallTimeout, so every other method in this file wraps withcontext.WithTimeout(..., nonStreamCallTimeout). Without it, a stalled upstream can hang the caller goroutine indefinitely.
🔧 Proposed fix
func (t *TogetherAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
if len(documents) == 0 {
return &RerankResponse{}, nil
}
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
+ if modelName == nil || strings.TrimSpace(*modelName) == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
- var region = "default"
- if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {
+ region := "default"
+ if apiConfig.Region != nil && *apiConfig.Region != "" {
region = *apiConfig.Region
}
- url := fmt.Sprintf("%s/%s", t.BaseURL[region], t.URLSuffix.Rerank)
-
- var topN = rerankConfig.TopN
- if rerankConfig.TopN != 0 {
- topN = rerankConfig.TopN
- }
+ baseURL, err := t.baseURLForRegion(region)
+ if err != nil {
+ return nil, err
+ }
+ url := fmt.Sprintf("%s/%s", baseURL, t.URLSuffix.Rerank)
reqBody := map[string]interface{}{
"model": *modelName,
"query": query,
"documents": documents,
- "top_n": topN,
+ }
+ if rerankConfig != nil && rerankConfig.TopN != 0 {
+ reqBody["top_n"] = rerankConfig.TopN
}
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+ ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+ defer cancel()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}Based on learnings, the shared httpClient here intentionally only sets transport.ResponseHeaderTimeout (no httpClient.Timeout), so a per-request context.WithTimeout is the legitimate overall deadline — matching every other method in this driver.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (t *TogetherAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | |
| return nil, fmt.Errorf("%s, no such method", t.Name()) | |
| if len(documents) == 0 { | |
| return &RerankResponse{}, nil | |
| } | |
| var region = "default" | |
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | |
| region = *apiConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", t.BaseURL[region], t.URLSuffix.Rerank) | |
| var topN = rerankConfig.TopN | |
| if rerankConfig.TopN != 0 { | |
| topN = rerankConfig.TopN | |
| } | |
| reqBody := map[string]interface{}{ | |
| "model": *modelName, | |
| "query": query, | |
| "documents": documents, | |
| "top_n": topN, | |
| } | |
| jsonData, err := json.Marshal(reqBody) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to marshal request: %w", err) | |
| } | |
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| resp, err := t.httpClient.Do(req) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to send request: %w", err) | |
| } | |
| defer resp.Body.Close() | |
| body, err := io.ReadAll(resp.Body) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to read response: %w", err) | |
| } | |
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("TogetherAI Rerank API error: status %d, body: %s", resp.StatusCode, string(body)) | |
| } | |
| var rerankResp struct { | |
| Results []struct { | |
| Index int `json:"index"` | |
| RelevanceScore float64 `json:"relevance_score"` | |
| } `json:"results"` | |
| } | |
| if err = json.Unmarshal(body, &rerankResp); err != nil { | |
| return nil, fmt.Errorf("failed to decode response: %w", err) | |
| } | |
| var rerankResponse RerankResponse | |
| for _, result := range rerankResp.Results { | |
| rerankResult := RerankResult{ | |
| Index: result.Index, | |
| RelevanceScore: result.RelevanceScore, | |
| } | |
| rerankResponse.Data = append(rerankResponse.Data, rerankResult) | |
| } | |
| return &rerankResponse, nil | |
| } | |
| func (t *TogetherAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | |
| if len(documents) == 0 { | |
| return &RerankResponse{}, nil | |
| } | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return nil, fmt.Errorf("api key is required") | |
| } | |
| if modelName == nil || strings.TrimSpace(*modelName) == "" { | |
| return nil, fmt.Errorf("model name is required") | |
| } | |
| region := "default" | |
| if apiConfig.Region != nil && *apiConfig.Region != "" { | |
| region = *apiConfig.Region | |
| } | |
| baseURL, err := t.baseURLForRegion(region) | |
| if err != nil { | |
| return nil, err | |
| } | |
| url := fmt.Sprintf("%s/%s", baseURL, t.URLSuffix.Rerank) | |
| reqBody := map[string]interface{}{ | |
| "model": *modelName, | |
| "query": query, | |
| "documents": documents, | |
| } | |
| if rerankConfig != nil && rerankConfig.TopN != 0 { | |
| reqBody["top_n"] = rerankConfig.TopN | |
| } | |
| jsonData, err := json.Marshal(reqBody) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to marshal request: %w", err) | |
| } | |
| ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout) | |
| defer cancel() | |
| req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData)) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| resp, err := t.httpClient.Do(req) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to send request: %w", err) | |
| } | |
| defer resp.Body.Close() | |
| body, err := io.ReadAll(resp.Body) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to read response: %w", err) | |
| } | |
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("TogetherAI Rerank API error: status %d, body: %s", resp.StatusCode, string(body)) | |
| } | |
| var rerankResp struct { | |
| Results []struct { | |
| Index int `json:"index"` | |
| RelevanceScore float64 `json:"relevance_score"` | |
| } `json:"results"` | |
| } | |
| if err = json.Unmarshal(body, &rerankResp); err != nil { | |
| return nil, fmt.Errorf("failed to decode response: %w", err) | |
| } | |
| var rerankResponse RerankResponse | |
| for _, result := range rerankResp.Results { | |
| rerankResult := RerankResult{ | |
| Index: result.Index, | |
| RelevanceScore: result.RelevanceScore, | |
| } | |
| rerankResponse.Data = append(rerankResponse.Data, rerankResult) | |
| } | |
| return &rerankResponse, nil | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/togetherai.go` around lines 497 - 570, The Rerank
method has multiple nil-dereference and logic issues: guard against nil
rerankConfig before accessing TopN and replace the redundant topN assignment
with a single defaulting expression (use a default value when rerankConfig is
nil or TopN==0), validate modelName is non-nil/non-empty before using *modelName
(same validation as Embed), require apiConfig and apiConfig.ApiKey to be non-nil
and return a clear error if missing before building the Authorization header,
replace direct t.BaseURL[region] usage with baseURLForRegion(region) to ensure a
valid base URL or return an error if missing, and create the request with a
context deadline (use context.WithTimeout and nonStreamCallTimeout, then
http.NewRequestWithContext) rather than bare http.NewRequest to avoid indefinite
hangs; update references in this function (Rerank, rerankConfig, modelName,
apiConfig, baseURLForRegion, nonStreamCallTimeout) accordingly.
| func (t *TogetherAIModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", t.Name()) | ||
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | ||
| return nil, fmt.Errorf("TogetherAI API key is missing") | ||
| } | ||
|
|
||
| if file == nil || *file == "" { | ||
| return nil, fmt.Errorf("file is missing") | ||
| } | ||
|
|
||
| region := "default" | ||
| if apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", t.BaseURL[region], t.URLSuffix.ASR) | ||
|
|
||
| var body bytes.Buffer | ||
| writer := multipart.NewWriter(&body) | ||
|
|
||
| // audio file | ||
| audioFile, err := os.Open(*file) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to open audio file: %w", err) | ||
| } | ||
| defer audioFile.Close() | ||
|
|
||
| part, err := writer.CreateFormFile("file", filepath.Base(*file)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create multipart file: %w", err) | ||
| } | ||
|
|
||
| if _, err = io.Copy(part, audioFile); err != nil { | ||
| return nil, fmt.Errorf("failed to copy audio data: %w", err) | ||
| } | ||
|
|
||
| // extra params | ||
| if asrConfig != nil && asrConfig.Params != nil { | ||
| for key, value := range asrConfig.Params { | ||
|
|
||
| var val string | ||
|
|
||
| switch v := value.(type) { | ||
| case string: | ||
| val = v | ||
| case bool: | ||
| val = strconv.FormatBool(v) | ||
| case int: | ||
| val = strconv.Itoa(v) | ||
| case float64: | ||
| val = strconv.FormatFloat(v, 'f', -1, 64) | ||
| default: | ||
| val = fmt.Sprintf("%v", v) | ||
| } | ||
|
|
||
| if err := writer.WriteField(key, val); err != nil { | ||
| return nil, fmt.Errorf("failed to write field %s: %w", key, err) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if err := writer.Close(); err != nil { | ||
| return nil, fmt.Errorf("failed to close multipart writer: %w", err) | ||
| } | ||
|
|
||
| // request | ||
| req, err := http.NewRequest("POST", url, &body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
| req.Header.Set("Content-Type", writer.FormDataContentType()) | ||
|
|
||
| resp, err := t.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| respBody, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response body: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("TogetherAI ASR error: %s - %s", resp.Status, string(respBody)) | ||
| } | ||
|
|
||
| // result | ||
| var result struct { | ||
| Text string `json:"text"` | ||
| } | ||
|
|
||
| if err := json.Unmarshal(respBody, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to unmarshal response: %w", err) | ||
| } | ||
|
|
||
| return &ASRResponse{ | ||
| Text: result.Text, | ||
| }, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Together AI audio transcriptions API multipart model field reference
💡 Result:
For the Together AI audio transcriptions API, the model field is a required string parameter within the multipart/form-data request body [1][2]. When making a POST request to the /audio/transcriptions endpoint, you must include the model as a form-data field to specify which transcription model (e.g., openai/whisper-large-v3) to use for the request [3][2]. Example usage with curl: curl -X POST "https://api.together.ai/v1/audio/transcriptions" \ -H "Authorization: Bearer $TOGETHER_API_KEY" \ -F "file=@audio.mp3;type=audio/mpeg" \ -F "model=openai/whisper-large-v3" In the Together AI SDKs, this is typically passed as a named argument in the create method: response = client.audio.transcriptions.create( file=Path("audio.mp3"), model="openai/whisper-large-v3") For a complete list of available models, refer to the Together AI model catalog [3][2]. Other parameters, such as language or prompt, may also be included as additional fields in the same multipart request [2][4].
Citations:
- 1: https://docs.together.ai/reference/audio-transcriptions
- 2: https://docs.together.ai/docs/inference/transcription/overview
- 3: https://togetherai-52386018.mintlify.app/docs/inference/transcription/overview
- 4: https://codesignal.com/learn/courses/advanced-transcription-features-and-optimization/lessons/customizing-transcription-with-language-and-prompt-parameters
Send model multipart field from modelName (and pass a request context)
TranscribeAudio accepts modelName, but it never writes the required Together AI /v1/audio/transcriptions multipart form field model, so the API will fall back to the default model and ignore the caller’s selection.
- No
writer.WriteField("model", ...)is made;modelNameis effectively unused. - Line ~641: use
http.NewRequestWithContext(...)instead ofhttp.NewRequest(...)so cancellation/timeouts are honored.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/togetherai.go` around lines 576 - 676, The
TranscribeAudio function never sends the required multipart "model" field (so
modelName is unused) and it uses http.NewRequest so request contexts/timeouts
aren't honored; update TranscribeAudio to accept a ctx context.Context
parameter, use writer.WriteField("model", *modelName) when modelName != nil &&
*modelName != "" (before writer.Close()), and create the HTTP request with
http.NewRequestWithContext(ctx, "POST", url, &body) so t.httpClient.Do honors
cancellation/timeouts; update all call sites of TranscribeAudio to pass the
caller's context.
| func (t *TogetherAIModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", t.Name()) | ||
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | ||
| return nil, fmt.Errorf("TogetherAI API key is missing") | ||
| } | ||
|
|
||
| if audioContent == nil || *audioContent == "" { | ||
| return nil, fmt.Errorf("text content is missing") | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", t.BaseURL[region], t.URLSuffix.TTS) | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, | ||
| "input": *audioContent, | ||
| } | ||
|
|
||
| if ttsConfig != nil && ttsConfig.Params != nil { | ||
| for key, value := range ttsConfig.Params { | ||
| reqBody[key] = value | ||
| } | ||
| } | ||
| if ttsConfig != nil && ttsConfig.Format != "" { | ||
| reqBody["response_format"] = ttsConfig.Format | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
|
|
||
| resp, err := t.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response body: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("%s - %s", resp.Status, string(body)) | ||
| } | ||
|
|
||
| return &TTSResponse{Audio: body}, nil | ||
| } |
There was a problem hiding this comment.
*modelName can panic; also missing request context.
- Line 699 —
*modelNameis dereferenced with no nil/empty validation. Every other method in this file guards this (seeEmbedlines 414-416,ChatWithMessagesline 155-157). - Line 717 — bare
http.NewRequest; for consistency with the rest of this file (and becausehttpClient.Timeoutis intentionally unset), this should wrap withcontext.WithTimeout(context.Background(), nonStreamCallTimeout)and usehttp.NewRequestWithContext.
🔧 Proposed fix
if audioContent == nil || *audioContent == "" {
return nil, fmt.Errorf("text content is missing")
}
+ if modelName == nil || strings.TrimSpace(*modelName) == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
@@
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
+ ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))Based on learnings, since this driver’s httpClient does not set an overall Timeout (only transport.ResponseHeaderTimeout), context.WithTimeout is the legitimate overall deadline and matches every other method in this file.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/togetherai.go` around lines 682 - 741, The AudioSpeech
method dereferences *modelName without validating it and uses http.NewRequest
without a request context; update TogetherAIModel.AudioSpeech to validate
modelName (nil and empty check like Embed/ChatWithMessages) before using it, and
create the POST request with a context deadline by wrapping a
context.WithTimeout(context.Background(), nonStreamCallTimeout) and calling
http.NewRequestWithContext so the request honors the shared nonStreamCallTimeout
and matches the rest of the file.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15107 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
implement rerank, asr, tts for TogetherAI
Type of change