go-openai icon indicating copy to clipboard operation
go-openai copied to clipboard

V1.40.1 Regression

Open cthackers opened this issue 6 months ago • 1 comments

When adding a file as a io.Reader to the transcription request, the 1.40.0 CreateFormFileReader used to call createFormFile which did the right thing, but now the in 1.40.1 was changed to create the form part differently and misses the Content-Type header so it's not accepted as a valid file. Can you please revert or fix this.

Thank you

cthackers avatar May 30 '25 18:05 cthackers

I know there is a reader there and you can't read from it, the file name is just "." so won't help, but you can do something like this

// CreateFormFileReader creates a multipart form part from an io.Reader with detected Content-Type.
func (fb *DefaultFormBuilder) CreateFormFileReader(fieldname string, r io.Reader, filename string) error {
	// Buffer to capture the first 512 bytes
	var buf bytes.Buffer
	tee := io.TeeReader(r, &buf)

	// Read up to 512 bytes for Content-Type detection
	data := make([]byte, 512)
	n, err := tee.Read(data)
	if err != nil && err != io.EOF {
		return fmt.Errorf("failed to read from reader for Content-Type detection: %w", err)
	}

	// Detect Content-Type
	contentType := http.DetectContentType(data[:n])

	// Create a new reader that includes the read bytes plus the rest
	combinedReader := io.MultiReader(&buf, r)

	// Set up MIME headers
	h := make(textproto.MIMEHeader)
	h.Set(
		"Content-Disposition",
		fmt.Sprintf(
			`form-data; name="%s"; filename="%s"`,
			escapeQuotes(fieldname),
			escapeQuotes(filepath.Base(filename)),
		),
	)
	h.Set("Content-Type", contentType)

	// Create the multipart part
	fieldWriter, err := fb.writer.CreatePart(h)
	if err != nil {
		return fmt.Errorf("failed to create form part: %w", err)
	}

	// Copy the full content to the form part
	_, err = io.Copy(fieldWriter, combinedReader)
	if err != nil {
		return fmt.Errorf("failed to copy reader to form part: %w", err)
	}

	return nil
}

cthackers avatar May 30 '25 18:05 cthackers