Skip to content

xyz-jphil/xyz-jphil-ai-gemini-oauth-tool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

xyz-jphil-ai-gemini-oauth-tool

A command-line tool for accessing Google Gemini API using OAuth authentication and the Code Assist API.

Java Maven License

Features

  • 🔐 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

Quick Start

Prerequisites

  • Java 21 or higher
  • Maven 3.8+
  • Google Cloud account with Code Assist API enabled

Installation

# 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

First-Time Setup

# 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 list

Usage

As a Library (Programmatic Access)

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

CLI Usage

Generate Content

# 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

Account Management

# 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>

Command Reference

Generate Command

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

Account Command

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

Supported Models

  • 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

File Attachments

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.

Configuration

Storage Locations

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 information
  • gemini_oauth_tokens/ - OAuth tokens (one file per account)
  • active-account.txt - Currently active account

Architecture

Project Structure

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

Dependencies

  • 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

API Integration

This tool uses Google's Code Assist API (cloudcode-pa.googleapis.com/v1internal) for enhanced capabilities. The tool automatically:

  1. Loads Code Assist settings on first use
  2. Retrieves your project ID
  3. Manages authentication tokens
  4. Handles automatic token refresh

Development

Building from Source

# Compile
mvn clean compile

# Run tests
mvn test

# Package
mvn package

# Install to local Maven repository
mvn install

Running Tests

The 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 test

All tests pass ✅

Troubleshooting

OAuth Authentication Failed

  • 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

Token Expired

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-active

Model Not Found (404)

Some models may not be available in all regions or projects:

  • Try using gemini-2.5-flash or gemini-2.5-pro
  • Verify Code Assist API is enabled for your project
  • Check your Google Cloud project permissions

No Active Account

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>

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes with tests
  4. Submit a pull request

License

This project is released into the public domain. You are free to use, modify, and distribute this software for any purpose without restriction.

Related Projects

  • xyz-jphil-ai-genai - The Code Assist API client library used by this tool
  • Google Gemini API - Official Gemini API documentation

Acknowledgments

  • Built with Google's Code Assist API
  • Uses the xyz-jphil-ai-genai library for API access
  • Inspired by Google's Gemini CLI tools

Support

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.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages