Wednesday, 5 March 2025

Building a Universal Java Client for Large Language Models

Building a Universal Java Client for Large Language Models

In today's rapidly evolving AI landscape, developers often need to work with multiple Large Language Model (LLM) providers to find the best solution for their specific use case. Whether you're exploring OpenAI's GPT models, Anthropic's Claude, or running local models via Ollama, having a unified interface can significantly simplify development and make it easier to switch between providers.

The Java LLM Client project provides exactly this: a clean, consistent API for interacting with various LLM providers through a single library. Let's explore how this library works and how you can use it in your Java applications.

Core Features

The library offers several key features that make working with LLMs easier:

  1. Unified Interface: Interact with different LLM providers through a consistent API
  2. Multiple Provider Support: Currently supports OpenAI, Anthropic, Google, Groq, and Ollama
  3. Chat Completions: Send messages and receive responses from language models
  4. Embeddings: Generate vector representations of text where supported
  5. Factory Pattern: Easily create service instances for different providers

Architecture Overview

The library is built around a few key interfaces and classes:

  • GenerativeAIService: The main interface for interacting with LLMs
  • GenerativeAIFactory: Factory interface for creating service instances
  • GenerativeAIDriverManager: Registry that manages available services
  • Provider-specific implementations in separate packages

This design follows the classic factory pattern, allowing you to:

  1. Register service factories with the GenerativeAIDriverManager
  2. Create service instances through the manager
  3. Use a consistent API to interact with different providers

Getting Started

To use the library, first add it to your Maven project:

xml
<dependency> <groupId>org.llm</groupId> <artifactId>llmapi</artifactId> <version>1.0.0</version> </dependency>


Basic Usage Example

Here's how to set up and use the library:

java
// Register service providers GenerativeAIDriverManager.registerService(OpenAIFactory.NAME, new OpenAIFactory()); GenerativeAIDriverManager.registerService(AnthropicAIFactory.NAME, new AnthropicAIFactory()); // Register more providers as needed // Create an OpenAI service Map<String, Object> properties = Map.of("apiKey", System.getenv("gpt_key")); var service = GenerativeAIDriverManager.create( OpenAIFactory.NAME, "https://api.openai.com/", properties ); // Create and send a chat request var message = new ChatMessage("user", "Hello, how are you?"); var conversation = new ChatRequest("gpt-4o-mini", List.of(message)); var reply = service.chat(conversation); System.out.println(reply.message()); // Generate embeddings var vector = service.embedding( new EmbeddingRequest("text-embedding-3-small", "How are you") ); System.out.println(Arrays.toString(vector.embedding()));

Working with Different Providers

OpenAI

java
Map<String, Object> properties = Map.of("apiKey", System.getenv("gpt_key")); var service = GenerativeAIDriverManager.create( OpenAIFactory.NAME, "https://api.openai.com/", properties ); // Chat with GPT-4o mini var conversation = new ChatRequest("gpt-4o-mini", List.of(new ChatMessage("user", "Hello, how are you?"))); var reply = service.chat(conversation);

Anthropic

java
Map<String, Object> properties = Map.of("apiKey", System.getenv("ANTHROPIC_API_KEY")); var service = GenerativeAIDriverManager.create( AnthropicAIFactory.NAME, "https://api.anthropic.com", properties ); // Chat with Claude var conversation = new ChatRequest("claude-3-7-sonnet-20250219", List.of(new ChatMessage("user", "Hello, how are you?"))); var reply = service.chat(conversation);

Ollama (Local Models)

java
// No API key needed for local models Map<String, Object> properties = Map.of(); var service = GenerativeAIDriverManager.create( OllamaFactory.NAME, "http://localhost:11434", properties ); // Chat with locally hosted Llama model var conversation = new ChatRequest("llama3.2", List.of(new ChatMessage("user", "Hello, how are you?"))); var reply = service.chat(conversation);

Under the Hood

The library uses an RPC (Remote Procedure Call) client to handle the HTTP communication with various APIs. Each provider's implementation:

  1. Creates appropriate request objects with the required format
  2. Sends requests to the corresponding API endpoints
  3. Parses responses into a consistent format
  4. Handles errors gracefully

The RpcBuilder creates proxy instances of service interfaces, handling the HTTP communication details so you don't have to.

Supported Models

The library currently supports several models across different providers:

  • OpenAI: all
  • Anthropic: all
  • Google: gemini-2.0-flash
  • Groq: all
  • Ollama: any other model you have locally

Extending the Library

One of the strengths of this design is how easily it can be extended to support new providers or features:

  1. Create a new implementation of GenerativeAIFactory
  2. Implement GenerativeAIService for the new provider
  3. Create necessary request/response models
  4. Register the new factory with GenerativeAIDriverManager

Conclusion

The Java LLM Client provides a clean, consistent way to work with multiple LLM providers in Java applications. By abstracting away the differences between APIs, it allows developers to focus on their application logic rather than the details of each provider's implementation.

Whether you're building a chatbot, generating embeddings for semantic search, or experimenting with different LLM providers, this library offers a straightforward way to integrate these capabilities into your Java applications.

The project's use of standard Java patterns like factories and interfaces makes it easy to understand and extend, while its modular design allows you to use only the providers you need. As the LLM ecosystem continues to evolve, this type of abstraction layer will become increasingly valuable for developers looking to build flexible, future-proof applications.


Link to github project - llmapi


Tuesday, 4 March 2025

Measuring Developer Productivity in Age on GENAI

The GenAI Revolution: Two Years Later

November 30, 2022 marked a pivotal moment when ChatGPT was released, sparking excitement and optimism about increased efficiency across industries. Now, with over two years of GenAI integration, the industry has matured enough to properly evaluate the impact and value of these tools on various aspects of business. In this post, I'll focus specifically on measuring developer productivity.

Measuring Impact: Output vs. Outcome

The impact of any change—whether new tools, processes, or methodologies—can be measured in terms of both output and outcome.

As a product organization, outcomes are ultimately the metrics that deliver revenue or customer growth. However, this same model cannot be directly applied when measuring the impact of GenAI on developer efficiency.

A Framework for Measurement

In this post, I'll share several approaches to measure productivity with GenAI tools, focusing on a progression from:

Output → Outcome → Growth

This framework will help organizations better understand how GenAI affects developer productivity in ways that eventually translate to business value.




Developer productivity can be measured on multiple dimensions






How Fast

(Output)

Is effective 

(Output)

Impact

(Outcome)

Growth

(Outcome)

Primary Metrics

# PR per Engineers


# Test Coverage per PR

# Engineering time Index


# Non Engineering time index 

Failure Rate of Change


Usage of Feature

Time spent on new capability/products 


Time spent on R&D

Secondary Metrics

Cycle Time for PR


Deployment Frequency


Perceived rate of productivity 


Time on PRs per sprint 


Friction in  delivery


Code tech Debt Index


Code Security Debt Index

Last minute change 


Operational & Security Health 

ROI on new features 


Revenue per Engineers


New Products/Segments  


 

Finding the Right Mix of Developer Productivity Metrics

The table above outlines four key dimensions for measuring developer productivity in the GenAI era. These dimensions incorporate both quantitative and qualitative metrics, collected through various methods:

Balanced Measurement Approach

Each dimension contains metrics that vary in nature:

  • Quantitative metrics provide objective, numerical data that can be tracked over time
  • Qualitative metrics capture subjective experiences and insights that numbers alone cannot reveal


Lets start with category of metrics 

How Fast ( Output)

This metric provides a straightforward measure of how effectively development teams leverage generative AI tools to produce code and the rate at which they do so. It serves as an excellent starting point for analysis and can be fully automated for continuous monitoring.


Is Effective ( Output)

This category assesses the quality of output by analyzing the ratio of time spent on engineering versus non-engineering tasks. It also incorporates lagging indicators such as sprint-level pull request review times, code technical debt indices, and security vulnerability indices. These metrics, largely automated, provide insights into both positive outcomes and potential side effects.

Impact ( Outcome)

This category marks the initial phase of measuring the impact of generative AI-assisted work. It focuses on evaluating delivery quality, product usage, and overall product health.

Growth ( Outcome)

This final category focuses on quantifying the tangible value generated by new features, specifically in terms of return on investment (ROI) and revenue. While direct revenue impact may not be immediately apparent in short development cycles, the focus shifts to measuring the time freed up for new capability development and the potential for new product or market segment expansion.

Things to watch while you measure developer productivity. 

Measuring productivity can lead to misleading signals. Organizations should be wary of:

  • Spikes in Lines of Code (LOC) that don't mean better output.
  • High Commit/PR counts without real progress.
  • Long hours, which often signal burnout, not efficiency.
  • Burning through story points too fast, which can mean poor planning.
  • Focusing only on individual metrics, not team success.
  • Using gamification that hurts collaboration.
  • Too many unfinished POCs or WIP projects.
  • Thinking Generative AI fixes everything
  • A pattern of implementing new Generative AI tools at an unsustainable frequency, such as weekly or more

Conclusion

Metrics shared in this post are in between DORA and SPACE and gives holistic view of team productivity gain. 

If you are early in journey then refer to Implementing-genai-in-engineering-teams post that talks about how to implement transformation.

Monday, 3 March 2025

Implementing GenAI in Engineering Teams - System Thinking Approach


In the rapidly evolving landscape of software development, Generative AI represents not just another tool, but a fundamental shift in how engineering teams operate. However, successful implementation requires more than just access to the latest AI tools—it demands a systematic approach to change management and team adaptation.


Challenges In GenAI Adoption

Many engineering teams rush to adopt GenAI tools like GitHub Copilot or Claude etc, hoping for immediate productivity gains. Yet, without a structured approach, these implementations often fall short of expectations or, worse, create new inefficiencies. The key lies in understanding that GenAI adoption is a systems challenge, not just a technical one.


A Systematic Framework for Implementation


Drawing from Donella Meadows' "Leverage Points" model, here's a practical framework for implementing GenAI in engineering teams, organised from foundational elements to transformative changes.


Start with the Foundations (Parameters & Buffers)



Before diving into complex transformations, establish your baseline:

- Set clear metrics for current development speed and quality

- Allocate 20% of team time for AI tool learning

- Maintain manual coding capabilities for A/B test

- Track costs and benefits per developer


Build the Structure


Structure your implementation around:

- A pilot team with clear objectives

- One primary AI tool (e.g., GitHub Copilot, Cursor , Aider , Windsurf etc)

- Specific use cases (test generation, documentation, new code , refactoring , code review etc)

- Regular feedback mechanisms


Optimize Information Flow


Success depends on effective knowledge sharing:


- Create an internal prompt library

- Document successful patterns and anti-patterns

- Establish clear guidelines on AI capabilities and limitations

- Regular updates on new AI features and best practices


Establish Clear Rules and Processes


Protect quality and security with:

- Mandatory review processes for AI-generated code

- Security scanning protocols for work produced by AI

- Data privacy guidelines

- Clear escalation paths for AI-related issues


Foster the Right Mindset


The most crucial transformation happens in how teams think about their work:


- Position AI as an augmentation tool, not a replacement

- Focus on high-value problem solving

- Encourage experimentation and learning

- Build confidence through small wins


Measuring Success


Track progress through:


Speed Metrics

   - Code completion time

   - Time saved on repetitive tasks

   - Documentation generation speed


Quality Indicators

   - Code review feedback

   - Bug detection rates

   - Technical debt metrics


Team Adaptation

   - AI tool usage rates

   - Prompt effectiveness

   - Knowledge sharing participation


Common Pitfalls to Avoid


Tool Overload: Starting with too many AI tools simultaneously

Unrealistic Expectations: Expecting perfect code from AI

Neglecting Training: Not investing in team AI literacy

Ignoring Process: Bypassing code review for AI-generated code

Poor Documentation: Not capturing lessons learned


The Path Forward

Successful GenAI implementation is a journey, not a destination. Start small, focus on concrete wins, and build momentum through systematic change. Remember that the goal isn't to replace human developers but to augment their capabilities and free them to focus on more complex, creative problem-solving.


Key Takeaways


1. Start with clear metrics and baseline measurements

2. Focus on one team and one tool initially

3. Build strong feedback loops and learning mechanisms

4. Maintain high quality standards

5. Foster a culture of experimentation and learning


The future of software development lies in the effective collaboration between human creativity and AI capabilities. Teams that can systematically implement these tools while maintaining their engineering excellence will find themselves at a significant advantage in the evolving technological landscape.

Remember, the goal isn't to completely transform overnight, but to build a sustainable, efficient system that leverages AI to enhance human capabilities rather than replace them.

Sunday, 7 July 2024

Top large language model to watch

The LLM landscape is exploding! With the immense potential of large language models, competition is fierce as companies race to develop the most powerful and innovative models. Training these models presents a lucrative business opportunity, attracting major players and startups alike.

Keeping track of the leaders is challenging. The LLM space is highly competitive, making it difficult to identify a single frontrunner. New versions are released constantly, pushing the boundaries of what's possible. While some might see this as a race to the bottom, it's more accurate to view it as rapid innovation that will ultimately benefit everyone.


Top company as of July,2024





Above diagram is in 2 groups , one for commercial ones and other one for hybrid(commercial/open weights) 

Commercial

OpenAI

This is poster child of LLMs, it has series of GPT* models. First large scale provider consumer LLMs.



GPT4-O is flagship model and all the models are available via API. This is very well funded and microsoft is behind this.

More details about model can be found at Open AI Model 

Research paper talking about GPT4 Model is available at 

GPT-4 Technical Report 

 GPT 1.0

GPT 2.0

Language Models are Few-Shot Learners

Evaluating Large Language Models Trained on Code

Amazon

Amazon has family of models called "Titan". Amazon Titan family of models incorporates Amazon’s 25 years of experience innovating with AI and machine learning across its business. Amazon Titan foundation models (FMs) provide customers with a breadth of high-performing image, multimodal, and text model choices, via a fully managed API.


More details about model can be found at Amazon Models

No research papers are available about amazon LLM model details. It is all propriety to keep competitive edge.


Antropic

Antropic is cofounded by some of ex Open AI employee. 


Anthropic's latest offering, Claude 3.5 Sonnet, has generated significant buzz. This powerful language model builds upon their previous success with Claude 3 Opus and is claimed to outperform OpenAI's GPT-4o, particularly in coding tasks.
Antropic is also very well funded, Amazon and google are major investor.

More details about model can be found at Antropic Models

Antropic models will be based on Open-AI type of architecture but they are focused on few research principal like 
AI as Systematic Science , safety and scaling 

One of the popular research paper from antropic is mapping-mind-language-model

MoasicML

MosaicML, co-founded by an MIT alumnus and a professor, made deep-learning models faster and more efficient. It was acquired by Databricks. 

Mosaic Pretrained Transformers (MPT) are GPT-style models with some special features -- Flash Attention for efficiency, ALiBi for context length extrapolation, and stability improvements to mitigate loss spikes.


More details about model can be found at mosaic ml

Some popular research papers are Train Short, Test Long and Flash attention


InflectionAI

Inflection AI focuses on developing a large language model (LLM) for personal use called Inflection.



Not much details is available about how model was trained but they claim - world's top empathetic Large Language Model (LLM)

More details about model can be found at inflection-2-5


Hybrid/Open Source

Google

Google inventor of famous paper Attention Is All You Need that became kernel of all the LLMs we see today. 
Google has been releasing LLM to community before Chatgpt came, Bert was one of the first model based on encoder/decoder and become foundation for many LLM that we see.







Google offers large language models (LLMs) across a spectrum of availability. Some models are fully commercial with open weights, meaning the underlying code is proprietary but the model outputs are accessible.

The Gemini family exemplifies this, with variants like Ultra, Pro (introduced in v1.5), Flash, and Nano catering to different needs in terms of size and processing power.

In contrast, Gemma is Google's open-source LLM family. It's designed for developers and researchers and comes in various sizes (e.g., Gemma 2B and 7B) for flexibility


Lots of reading material is available from google on LLM and Gemma models, some of the popular ones are 


Meta

Meta builds LLama series of model, these are open source and Meta designed Llama to be efficient, achieving good performance while being trained on publicly available datasets.



Llama3 is most recent and state of art. These models are trained by meta and made available via various hosting platform. Llama3 is is extended by other vendors like Gradient , Nvidia , dolphin etc.

Details about model is available at llama3. 

Meta has publish lots of paper from first version of model, some of the popular ones are 




Mistral

Mistral is french based company and they release all model weights under Apache 2.0.
Mistral strives to create efficient models that require less computational power compared to some competitors. This makes them more accessible to a wider range of users.

Mistral innovation is around Grouped Query Attention (GQA). Some of the recent models are based on Mixture Of Expert.




More details about model is available at Mistral models



DataBricks

Databricks is building open source model that are based on MOE. Most recent and state of the art model is DBRX.





Details about model is available at introducing-dbrx-new-state-art-open-llm


Some of popular research papers are 

Cohere

Cohere is canadian based company. They build model called CommandR, it is a state-of-the-art RAG-optimized model designed to tackle enterprise-grade workloads.



More details about model can be found at Command-R

Some of popular research papers are RLHF Can Speak Many Languages: Unlocking Multilingual Preference Optimization for LLMs

 

Microsoft

While Microsoft leverages OpenAI's powerful GPT-4 language models for some functionalities, they've also made significant contributions to open-source AI with the Phi-3 family of models.

Phi-3 models are a type of small language model (SLM), specifically designed for efficiency and performance on mobile devices and other resource-constrained environments.



 More details about model can be found at phi-3

Some of popular research papers related to Phi series model are Textbooks Are All You Need , Textbooks Are All You Need II and Phi-3 Technical Report


Conclusion

We are witnessing an interesting time where many large language model (LLM) models are available for building apps, accessible to both consumers and developers. Predicting the dominant player is difficult due to the rapidly changing landscape.

One key concept to grasp is that the GENAI stack is multifaceted. Foundation models are just one layer, and they can be quite expensive due to hardware requirements. Training a foundation model can easily cost millions of dollars, making it difficult for companies to maintain a competitive edge.

As software engineers, we need to leverage this technology by selecting the best model for each specific use case. Defining "best" can be subjective, and the answer often depends on various factors.

Here's a crucial consideration: while using the top-performing LLM might be tempting, it's vital to maintain a flexible architecture. This allows you to easily switch to newer LLMs, similar to how we switch between databases or other vendor-specific technologies.

In the next part of this blog, I'll explore the inference side of LLMs, a fascinating area that will ultimately determine the return on investment (ROI) for companies making significant investments in this technology.

Saturday, 23 March 2024

Say Goodbye to Boilerplate: Annotating Your Way to Powerful API Clients

Ever feel like writing boilerplate code for every single REST API call?

Constructing URLs, managing parameters, setting headers, crafting bodies - it's all time-consuming and repetitive. Wouldn't it be amazing if, like ORMs for databases, there was a way to simplify API interactions?

Well, you're in luck!

This post will introduce you to the concept of annotation-based RPC clients, a powerful tool that can dramatically reduce your API coding burden. We'll explore how annotations can automate the tedious parts of API calls, freeing you to focus on the real logic of your application.


I will use search engine API as example to demonstrate how it will look like.


public interface GoogleSearchService {

@XGET("/customsearch/v1")
@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("key") String apiKey,
                                @XQuery("cx") String context,
                              @XQuery(value = "q", encoded = true) String searchTerm);




}


This approach uses annotations to declaratively specify everything about the API call. This declarative style offers several advantages:

  • Familiar Programming Experience: The syntax feels like you're interacting with a normal programming API, making it intuitive and easy to learn.
  • Abstraction from Implementation Details: You don't need to worry about the internal names of parameters or the specifics of the underlying protocol. The annotations handle those details for you.
  • Simplified Error Handling: The RpcReply abstraction encapsulates error handling, providing a clean and consistent way to manage potential issues.
  • Seamless Asynchronous Support: Adding asynchronous execution becomes straightforward, allowing you to make non-blocking API calls without extra effort.
  • Enhanced Testability: Everything related to the API interaction is defined through the interface, making unit testing a breeze. You can easily mock the interface behavior to isolate your application logic.

Lets have look at RpcReply abstraction 


public interface RpcReply<T> {

T value();
void execute();
int statusCode();
boolean isSuccess();
Optional<String> reply();
Optional<String> error();
Optional<Exception> exception();
}


The RpcReply object plays a crucial role in this approach. It's a lazy object, meaning its execution is deferred until explicitly requested. This allows you to choose between synchronous or asynchronous execution depending on your needs.

More importantly, RpcReply encapsulates error handling. It takes care of any errors that might occur during the actual API call. You can access the response data or any potential errors through a clean and consistent interface provided by RpcReply. This eliminates the need for manual error handling code within your application logic.


One more thing is missing, reply using map is not neat, it will be better if it is strongly type object like Searchresult.

In essence, using strongly typed objects provides a cleaner, more reliable, and more maintainable way to work with API responses.


Lets add StrongType to our API, it will look something like this.


public interface GoogleSearchService {

@XGET("/customsearch/v1")
@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("key") String apiKey,
    @XQuery("cx") String context,
     @XQuery(value = "q", encoded = true) String searchTerm);

@XGET("/customsearch/v1")
@XHeaders({"Content-Type: application/json"})
RpcReply<GoogleSearchResult> find(@XQuery("key") String apiKey,
    @XQuery("cx") String context,
    @XQuery(value = "q", encoded = true) String searchTerm);


}


Let's dive into how we can write code that interprets declarative definitions and translates them into actual HTTP API calls.

There are several approaches to generate the code behind this interface:

  • Build Plugin: This method utilizes a build plugin to generate actual code during the compilation process.
  • Dynamic Proxy: This approach employs a dynamic proxy that can leverage the provided metadata to generate real API calls at runtime.

Many frameworks leverage either of these options, or even a combination of both. In the solution I'll share, we'll be using Dynamic Proxy.


I have written about dynamic proxy in past, you can read this if new to concept or need refresher

dynamic-proxy

more-on-dynamic-proxy



High Level Sketch of implementation




In this step, we create a proxy object. This proxy will act as an intermediary between the client application and the real server. It can intercept all outgoing calls initiated by the client app.




During this stage, the client interacts with a remote proxy object. This proxy acts as a transparent intermediary, intercepting all outgoing calls.

Here's what the proxy does:

  • Builds metadata: The proxy can gather additional information about each call, such as timestamps, user IDs, or call identifiers. This metadata can be valuable for debugging, logging, or performance analysis.
  • Makes the server call: Once it has the necessary information, the proxy forwards the request to the actual server.
  • Handles errors: If the server call encounters any issues, the proxy can gracefully handle the error and provide a meaningful response back to the client.
  • Parses the response: The proxy can interpret the server's response and potentially transform it into a format that's easier for the client to understand. This can include type safety checks to ensure the returned data matches the expected format.


Code snippet that build Rpc Stack Trace


HttpCallStack callStack = new HttpCallStack(builder.client());
_processMethodTags(method, callStack);
_processMethodParams(method, args, callStack);
callStack.returnType = returnTypes(method);
return callStack;


Full code of proxy is available at ServiceProxy.java


Lets look at few examples of client service interface.


public interface DuckDuckGoSearch {
@XGET("/ac")
@XHeaders({"Content-Type: application/json"})
RpcReply<List<Map<String, Object>>> suggestions(@XQuery(value = "q", encoded = true) String searchTerm);

@XGET("/html")
@XHeaders({"Content-Type: application/json"})
RpcReply<String> search(@XQuery(value = "q", encoded = true) String searchTerm);

}


public interface DuckDuckGoService {
@XGET("/search.json")
@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("api_key") String apiKey, @XQuery("engine") String engine, @XQuery(value = "q", encoded = true) String searchTerm);

@XGET("/search.json")
@XHeaders({"Content-Type: application/json"})
RpcReply<DuckDuckGoSearchResult> query(@XQuery("api_key") String apiKey, @XQuery("engine") String engine, @XQuery(value = "q", encoded = true) String searchTerm);
}

public interface GoogleSearchService {

@XGET("/customsearch/v1")
@XHeaders({"Content-Type: application/json"})
RpcReply<Map<String, Object>> search(@XQuery("key") String apiKey, @XQuery("cx") String context, @XQuery(value = "q", encoded = true) String searchTerm);

@XGET("/customsearch/v1")
@XHeaders({"Content-Type: application/json"})
RpcReply<GoogleSearchResult> find(@XQuery("key") String apiKey, @XQuery("cx") String context, @XQuery(value = "q", encoded = true) String searchTerm);


}


Client code is very lean, it looks something like this

RpcBuilder builder = new RpcBuilder().serviceUrl("https://www.googleapis.com");
GoogleSearchService service = builder.create(GoogleSearchService.class);

String key = System.getenv("google_search");

RpcReply<Map<String, Object>> r = service.search(key, "61368983a3efc4386", "large language model");
r.execute();
Map<String, Object> value = r.value();
List<Map<String, Object>> searchResult = (List<Map<String, Object>>) value.get("items");

searchResult.forEach(v -> {
System.out.println(v.get("title") + " -> " + v.get("link"));
});

RpcReply<GoogleSearchResult> searchResults = service.find(key, "61368983a3efc4386", "large language model");

searchResults.execute();

searchResults.value().items.forEach(System.out::println);


Full client code is available @ APIClient.java


Conclusion

Dynamic proxies offer a powerful approach to abstraction, providing several benefits:

  • Protocol Independence: The underlying communication protocol can switch from HTTP to something entirely new (e.g., gRPC, custom protocols) without requiring any changes to the client code. The dynamic proxy acts as an intermediary, insulating the client from the specifics of the protocol being used.
  • Enhanced Functionality: Dynamic proxies can add valuable features to client interactions. This can include:
    • Caching: The proxy can store responses to frequently accessed data, reducing load on the server and improving performance.
    • Throttling: The proxy can limit the rate of calls made to the server to prevent overloading or comply with usage quotas.
    • Telemetry: The proxy can collect data about client-server interactions, providing insights into system performance and user behavior.

By leveraging dynamic proxies, you can achieve a clean separation between the client's core logic and the communication details. This promotes loose coupling, making your code more adaptable, maintainable, and easier to test.

This approach leads us towards a concept similar to API Relational Mapping (ARM) (though this term isn't widely used). Think of it as a specialized layer that translates between API calls and the underlying functionalities they trigger.


Full client library is available @ rpcclient.