Skip to content

Go: implement rerank, asr, tts for TogetherAI - #15107

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
May 21, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement rerank, asr, tts for TogetherAI

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels May 21, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed 💞 feature Feature request, pull request that fullfill a new feature. labels May 21, 2026
@Haruko386
Haruko386 marked this pull request as draft May 21, 2026 11:21
@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extends TogetherAI provider support by implementing four API method stubs: Rerank for document scoring, TranscribeAudio for ASR via file upload, AudioSpeech for TTS, and AudioSpeechWithSender for streaming TTS with base64 audio delta decoding. Configuration is expanded with matching endpoint routes and model definitions.

Changes

TogetherAI Provider Method Implementation

Layer / File(s) Summary
Configuration endpoints and models
conf/models/togetherai.json
TogetherAI url_suffix mapping extended to include rerank, asr, and tts routes alongside embedding; three new model definitions added for reranking, audio transcription, and text-to-speech with corresponding endpoint identifiers.
Required imports for implementations
internal/entity/models/togetherai.go
Import list extended to support base64 encoding/decoding, multipart form uploads, file path handling, and string-to-number conversions.
Rerank method implementation
internal/entity/models/togetherai.go
Rerank constructs and sends HTTP POST request with document payload, receives upstream results array, and maps each result into RerankResponse entries.
Audio transcription implementation
internal/entity/models/togetherai.go
TranscribeAudio opens and uploads audio file via multipart form-data, appends optional configuration parameters, validates HTTP response, and unmarshals returned JSON text into ASRResponse.
Text-to-speech implementations
internal/entity/models/togetherai.go
AudioSpeech sends JSON request with text and format options, returns raw audio bytes as TTSResponse.Audio; AudioSpeechWithSender performs streaming SSE POST, decodes base64 audio delta payloads, and forwards chunks to provided callback until [DONE] terminator.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#14608: Implements Rerank method in ZhipuAI model driver by calling /rerank endpoint and translating upstream results into score arrays.
  • infiniflow/ragflow#14957: Extends TogetherAI provider by implementing previously-stubbed driver methods and expanding configuration with matching endpoints and models.
  • infiniflow/ragflow#14813: Implements Rerank method in LocalAI model driver and adds corresponding provider endpoint configuration.

Suggested labels

ci, size:L


🐰 Four methods hopped in line,
Rerank, transcribe, and speakers fine,
With base64 streams that play and dance,
TogetherAI gets its full advance! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement rerank, asr, tts for TogetherAI' clearly and concisely summarizes the main change—implementing three new features (rerank, ASR, TTS) for TogetherAI in Go, matching the actual additions in both config and implementation files.
Description check ✅ Passed The PR description addresses the template requirements with a problem statement and correctly marks the change type as a new feature. However, it lacks substantive detail about the implementation approach, use cases, or testing information.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Haruko386
Haruko386 marked this pull request as ready for review May 21, 2026 11:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 775ea55 and ec74dfd.

📒 Files selected for processing (2)
  • conf/models/togetherai.json
  • internal/entity/models/togetherai.go

Comment on lines +58 to +64
{
"name": "mixedbread-ai/mxbai-rerank-large-v2",
"max_tokens": "16384",
"model_types": [
"rerank"
]
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
{
"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).

Comment on lines 497 to 570
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Multiple nil-dereference panics + dead branch in Rerank.

Several runtime panics are reachable here, plus a redundant block:

  1. Line 509 — rerankConfig.TopN will panic if rerankConfig is nil. The method signature accepts *RerankConfig but the code never checks it.
  2. Line 515 — *modelName will panic if modelName is nil or empty (no validation, unlike Embed at lines 414-416).
  3. Line 532 — *apiConfig.ApiKey will panic if apiConfig is nil or apiConfig.ApiKey is nil. The earlier check at line 503 only guards apiConfig for region lookup, not for the auth header.
  4. Line 509-512 — var topN = rerankConfig.TopN; if rerankConfig.TopN != 0 { topN = rerankConfig.TopN } — both branches assign the same value; the if is dead code.
  5. 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.
  6. Line 526 — uses bare http.NewRequest with no context/deadline. The shared httpClient only sets transport.ResponseHeaderTimeout, not an overall Timeout, so every other method in this file wraps with context.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.

Suggested change
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.

Comment on lines 576 to 676
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 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:


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; modelName is effectively unused.
  • Line ~641: use http.NewRequestWithContext(...) instead of http.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.

Comment on lines 682 to 741
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

*modelName can panic; also missing request context.

  • Line 699 — *modelName is dereferenced with no nil/empty validation. Every other method in this file guards this (see Embed lines 414-416, ChatWithMessages line 155-157).
  • Line 717 — bare http.NewRequest; for consistency with the rest of this file (and because httpClient.Timeout is intentionally unset), this should wrap with context.WithTimeout(context.Background(), nonStreamCallTimeout) and use http.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

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (440153c) to head (ec74dfd).
⚠️ Report is 21 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 1ece1c8 into infiniflow:main May 21, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants