Skip to content

Instantly share code, notes, and snippets.

@chew-z
Created September 25, 2025 20:05
Show Gist options
  • Save chew-z/4dfd49777b383a19716a15d2d5834cf2 to your computer and use it in GitHub Desktop.
Save chew-z/4dfd49777b383a19716a15d2d5834cf2 to your computer and use it in GitHub Desktop.
Upload PDF and ask question vs OpenAI Responses API
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"strings"
_ "github.com/joho/godotenv/autoload"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
"github.com/openai/openai-go/v2/responses"
)
func main() {
ctx := context.Background()
args := os.Args
if len(args) < 2 {
log.Fatalln("Usage: ./responses-input-file <file name>")
}
filePath := args[1]
fileName := filepath.Base(filePath)
fileExt := filepath.Ext(fileName)
if strings.ToLower(fileExt) != ".pdf" {
log.Fatalln("Input file must be .pdf")
}
// Create a new OpenAI client
oaiClient := openai.NewClient(
option.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)
fileReader, err := os.Open(filePath)
if err != nil {
log.Fatalln(err.Error())
}
// Upload PDF file to OpenAI API
inputFile := openai.File(fileReader, fileName, "application/pdf")
storedFile, err := oaiClient.Files.New(ctx, openai.FileNewParams{
File: inputFile,
Purpose: openai.FilePurposeUserData,
})
if err != nil {
log.Fatalf(fmt.Sprintf("error uploading file to OpenAI: %s", err.Error()))
return
}
// Ask question (prompt) towards uploaded PDF file using Responses API
params := responses.ResponseNewParams{
Model: openai.ResponsesModelGPT5Codex,
}
params.Input = responses.ResponseNewParamsInputUnion{
OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(
responses.ResponseInputMessageContentListParam{
responses.ResponseInputContentUnionParam{
OfInputFile: &responses.ResponseInputFileParam{
FileID: openai.String(storedFile.ID),
Type: "input_file",
},
},
responses.ResponseInputContentUnionParam{
OfInputText: &responses.ResponseInputTextParam{
Text: "Read provided document and prepare short, comprehensive guide with examples on using OpenAI Responses API with Golang",
Type: "input_text",
},
},
},
"user",
),
},
}
resp, err := oaiClient.Responses.New(ctx, params)
if err != nil {
log.Fatalln(err.Error())
}
// Print reponse
log.Println(resp.OutputText())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment