0

I use AI only for translating korean into English and arranging my text.

I'm working with the Google GenAI Java SDKcom.google.genai:google-genai:1.23.0 — in a Spring Boot 3 application, running inside a GitHub Codespaces environment.

I’m calling the Gemini 2.5 Flash model like this:

GenerateContentResponse response = geminiClient.models()
    .generateContent(modelName, prompt, generationConfig);

String answer = response.text(); // This part works well

Now, I want to log the token usage information, such as:

  • prompt token count
  • candidates token count
  • total token count

I understand this should come from usageMetadata(), but I cannot seem to access the fields correctly.


  • I'm using GitHub Codespaces, so I can't easily “Ctrl + click” into class definitions to explore available methods.
  • I’ve searched the official SDK documentation and Javadocs, but I couldn’t find any clear documentation for the GenerateContentResponseUsageMetadata class or its available methods.
  • I’ve also searched online (GitHub, Google, Dev forums), and some posts suggest that usageMetadata may not be exposed reliably in some SDK versions or model responses.
  • I’ve confirmed that response.toString() does sometimes include usageMetadata as a JSON fragment, e.g.:
"usageMetadata": {
  "promptTokenCount": 30,
  "candidatesTokenCount": 65,
  "totalTokenCount": 95
}

So the data exists — I just can’t access it via the Java SDK directly.


  1. What is the correct way to import and use usageMetadata() in v1.23.0?
  2. What are the exact method names (if any) to retrieve the token counts?
  3. Is this feature even fully supported in SDK v1.23.0, or should I parse the raw JSON manually as a workaround?

Any advice or examples would be much appreciated — especially from anyone who has successfully retrieved token usage in Java using the Gemini 2.5 Flash model.

Thanks in advance!

I attempted the following:

import com.google.genai.types.GenerateContentResponseUsageMetadata;

...

GenerateContentResponseUsageMetadata usage = response.usageMetadata().orElse(null);

if (usage != null) {
    int promptTokens = usage.getPromptTokenCount();  // error
    int completionTokens = usage.getCandidatesTokenCount();  // error
    int totalTokens = usage.getTotalTokenCount();  // error
}

But I keep getting "cannot find symbol" errors for all three method calls above, suggesting the methods don’t exist.

I also tried calling them without get, like usage.promptTokenCount(), but that didn’t work either.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.