A command-line tool for accessing Google Gemini API using OAuth authentication and the Code Assist API.
- 🔐 OAuth Authentication - Use OAuth tokens instead of API keys
- 👥 Multi-Account Support - Manage multiple Google accounts
- 🔄 Auto Token Refresh - Automatically refreshes expired tokens
- 📎 File Attachments - Attach multiple files to prompts
- 🎯 Model Selection - Choose from gemini-2.5-pro, gemini-2.5-flash, and more
- 💾 Flexible Output - Write to console or file
- 🛠️ Code Assist API - Uses Google's Code Assist API for enhanced capabilities
- Java 21 or higher
- Maven 3.8+
- Google Cloud account with Code Assist API enabled
# Clone the repository
git clone https://github.com/xyz-jphil/xyz-jphil-ai-gemini-oauth-tool.git
cd xyz-jphil-ai-gemini-oauth-tool
# Build the project
mvn clean package
# The JAR will be created at:
# target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar# 1. Add an OAuth account (opens browser for authentication)
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar account add --set-active
# 2. Verify the account was added
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar account listYou can use this tool as a Maven dependency in your Java projects for programmatic access with OAuth management:
<!-- Add to your pom.xml -->
<dependency>
<groupId>io.github.xyz-jphil</groupId>
<artifactId>xyz-jphil-ai-gemini-oauth-tool</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>Simple Usage (High-Level API via xyz-jphil-ai-genai):
import xyz.jphil.ai.gemini.oauth.CodeAssistOAuth;
import io.github.xyz.jphil.ai.genai.client.CodeAssistApiClient;
import com.google.genai.types.*;
// Create OAuth manager (uses active account by default)
CodeAssistOAuth oauth = CodeAssistOAuth.builder().build();
// Get high-level client
CodeAssistApiClient client = oauth.client();
// Build request
Content content = Content.builder()
.role("user")
.parts(Part.fromText("Explain quantum computing"))
.build();
// Generate content
GenerateContentResponse response = client.generateContent(
"gemini-2.5-flash",
List.of(content),
GenerateContentConfig.builder().build(),
oauth.projectId(),
oauth.accessToken()
);
// Process response
String text = response.candidates().get().get(0)
.content().get().parts().get().get(0).text().get();
System.out.println(text);Advanced Usage (Low-Level API via googleapis/java-genai):
import xyz.jphil.ai.gemini.oauth.CodeAssistOAuth;
import com.google.genai.GenerativeModel;
// Create OAuth manager
CodeAssistOAuth oauth = CodeAssistOAuth.builder()
.rotationStrategy(CodeAssistOAuth.RotationStrategy.ROUND_ROBIN)
.build();
// Option 1: Get credentials and create model yourself
var creds = oauth.credentials();
GenerativeModel model = GenerativeModel.builder()
.modelName("gemini-2.5-flash")
.projectId(creds.projectId())
.accessToken(creds.accessToken())
.build();
// Now you have FULL access to googleapis/java-genai features:
// - Streaming responses
// - Thoughts API
// - Function calling
// - Context caching
// - Advanced generation config
GenerateContentResponse response = model.generateContent(...);Multi-Account with Load Distribution:
CodeAssistOAuth oauth = CodeAssistOAuth.builder()
.rotationStrategy(CodeAssistOAuth.RotationStrategy.ROUND_ROBIN)
.build();
// Automatically rotates through accounts
for (int i = 0; i < 100; i++) {
String token = oauth.accessTokenRoundRobin(); // Different account each time
String projectId = oauth.projectId();
// Use token and projectId for API call
}
// Other strategies:
String token1 = oauth.accessTokenLRU(); // Least recently used
String token2 = oauth.accessTokenRandom(); // Random selection
String token3 = oauth.accessToken(RotationStrategy.ROUND_ROBIN);Key Features:
- ✅ Auto Token Refresh - Tokens automatically refresh when expired (60s buffer)
- ✅ Auto Project ID Loading - Project ID loaded from Code Assist API and cached
- ✅ Multi-Account - Manage multiple accounts, switch between them
- ✅ Account Rotation - Round-robin, LRU, random strategies for load distribution
- ✅ Fluent API - Builder pattern with Lombok fluent accessors
- ✅ JEMTR Compatible - Shares OAuth accounts/tokens with other xyz-jphil projects
See Also:
examples/SimpleExample.java- Basic usage exampleexamples/MultiAccountExample.java- Multi-account load distribution
# Simple prompt
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar generate \
--prompt "Explain quantum computing in simple terms"
# With file attachments
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar generate \
--prompt "Analyze this code" \
--attach Main.java \
--attach Utils.java
# With specific model
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar generate \
--model gemini-2.5-pro \
--prompt "Translate this document" \
--attach document.txt
# Output to file
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar generate \
--prompt "Generate a report on AI trends" \
--output report.md
# Read prompt from file
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar generate \
--prompt @my-prompt.txt \
--output result.txt# List all accounts
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar account list
# Set active account
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar account set-active <account-id>
# Remove account
java -jar target/xyz-jphil-ai-gemini-oauth-tool-1.0-SNAPSHOT-jar-with-dependencies.jar account remove <account-id>java -jar xyz-jphil-ai-gemini-oauth-tool.jar generate [OPTIONS]
Options:
-p, --prompt <text> Prompt text or @file to read from file (required)
-m, --model <model> Model to use (default: gemini-2.0-flash-exp)
-a, --attach <file> Files to attach to the prompt (can be used multiple times)
-o, --output <file> Write output to file instead of stdout
--account <id> Account ID to use (default: active account)
-h, --help Show help message
java -jar xyz-jphil-ai-gemini-oauth-tool.jar account <subcommand>
Subcommands:
add Add a new OAuth account
--set-active Set this account as active
--email <email> Email hint for authentication
list List all OAuth accounts
set-active <id> Set the active OAuth account
remove <id> Remove an OAuth account
--force Skip confirmation prompt
gemini-2.5-pro- Most capable model (recommended)gemini-2.5-flash- Fast and efficient (recommended)gemini-2.0-flash-exp- Experimental flash model- Other models as supported by Code Assist API
The tool supports attaching multiple files to prompts. Supported formats include:
- Text files:
.txt,.md,.json,.xml,.html - Code files:
.java,.js,.py,.cpp, etc. - Images:
.jpg,.png,.gif,.webp - Documents:
.pdf
Files are Base64-encoded and sent inline with the prompt.
The tool stores configuration in your home directory:
- Windows:
C:\Users\<username>\xyz-jphil\ai\gemini-oauth-tool\ - Linux/Mac:
~/.gemini-oauth/
Files stored:
gemini_oauth_accounts.xml- Account informationgemini_oauth_tokens/- OAuth tokens (one file per account)active-account.txt- Currently active account
xyz-jphil-ai-gemini-oauth-tool/
├── src/main/java/xyz/jphil/ai/gemini/oauth/
│ ├── account/ # Account management
│ ├── cli/ # CLI commands (picocli)
│ ├── model/ # Data models
│ ├── oauth/ # OAuth flow and token handling
│ └── Main.java # Entry point
├── src/test/java/ # Unit tests (46 tests)
└── pom.xml # Maven configuration
- xyz-jphil-ai-genai - Code Assist API client library
- picocli - CLI framework
- lombok - Boilerplate reduction
- jackson - JSON/XML serialization
- google-auth-library - OAuth support
- slf4j/logback - Logging
This tool uses Google's Code Assist API (cloudcode-pa.googleapis.com/v1internal) for enhanced capabilities. The tool automatically:
- Loads Code Assist settings on first use
- Retrieves your project ID
- Manages authentication tokens
- Handles automatic token refresh
# Compile
mvn clean compile
# Run tests
mvn test
# Package
mvn package
# Install to local Maven repository
mvn installThe project includes 46 unit tests covering:
- OAuth token handling and expiry logic
- Account management operations
- Token storage and retrieval
- OAuth service with auto-refresh
mvn testAll tests pass ✅
- Ensure you have Code Assist API enabled in your Google Cloud project
- Check that OAuth credentials are configured correctly
- Try removing and re-adding the account
Tokens are automatically refreshed. If you see token errors:
# Remove the old account
java -jar target/xyz-jphil-ai-gemini-oauth-tool.jar account remove <account-id>
# Add it again
java -jar target/xyz-jphil-ai-gemini-oauth-tool.jar account add --set-activeSome models may not be available in all regions or projects:
- Try using
gemini-2.5-flashorgemini-2.5-pro - Verify Code Assist API is enabled for your project
- Check your Google Cloud project permissions
If you see "No active account set":
# List accounts to find the ID
java -jar target/xyz-jphil-ai-gemini-oauth-tool.jar account list
# Set one as active
java -jar target/xyz-jphil-ai-gemini-oauth-tool.jar account set-active <account-id>Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Submit a pull request
This project is released into the public domain. You are free to use, modify, and distribute this software for any purpose without restriction.
- xyz-jphil-ai-genai - The Code Assist API client library used by this tool
- Google Gemini API - Official Gemini API documentation
- Built with Google's Code Assist API
- Uses the xyz-jphil-ai-genai library for API access
- Inspired by Google's Gemini CLI tools
For issues and questions:
- Open an issue on GitHub
- Check the troubleshooting section above
- Review the command help:
java -jar xyz-jphil-ai-gemini-oauth-tool.jar --help
Note: This tool requires OAuth authentication and Code Assist API access. You need:
- A Google Cloud account
- Code Assist API enabled
- OAuth credentials configured
The tool will guide you through the authentication process on first use.