Implementing Function Calling with Gemini in Next.js

A practical look at Gemini function calling in my Next.js salary and tax assistant, from tool declarations and dispatch to returning calculation results.

AI Engineering2026-10-09

When I started building AI-powered applications, I wanted an assistant that could do more than answer questions. I wanted it to use the same calculation logic as the rest of my application instead of guessing numbers based on a prompt.

For example, if someone asks about their monthly take-home salary, the assistant should use the actual salary calculation logic rather than generate an estimate from its training data.

I implemented this in my AI Assist feature, which supports salary, income tax, HRA exemption, and provident fund (PF) calculations.

In this post, I'll walk through how function calling works, how I connected Gemini to existing application logic, and what I learned while implementing it.

Function calling and tool calling

Function calling allows an LLM to request the execution of a specific function by providing its name and structured arguments.

The important distinction is that the model requests the function call, but the application executes the function.

For example, when a user asks for a salary calculation, Gemini can identify that a salary calculator is needed and generate a structured request containing the annual CTC. My application then validates the input, executes the calculation, and returns the result to Gemini.

Function calling and tool calling are often used interchangeably. Tool calling is also used as a broader term for giving an LLM access to capabilities such as functions, APIs, and document search.

In my implementation, Gemini uses function declarations to access four specific calculation capabilities. It isn't a general-purpose agent that can call arbitrary APIs or execute any function in my application.

Why I needed function calling

Consider this question:

My CTC is ₹20 LPA. What will be my monthly take-home salary?

A regular chatbot can explain the factors that affect take-home salary, including income tax, provident fund, and other deductions. However, I don't want it to calculate these values purely through its language model.

I already have calculation logic in my application. I wanted the AI assistant to understand the user's request and invoke the appropriate calculation.

The flow I wanted was straightforward:

  1. Understand the user's question.
  2. Identify the appropriate calculation function.
  3. Generate the required arguments.
  4. Execute the existing calculation logic.
  5. Return the calculated result to Gemini.
  6. Generate a user-friendly explanation using that result.

This allows me to combine the flexibility of an LLM with deterministic application logic.

How the implementation works

The function-calling flow involves the browser, my Next.js backend, Gemini, and the existing calculation functions.

User asks a question
        |
        v
Next.js API
        |
        v
Gemini receives the question and tool declarations
        |
        v
Gemini requests a function call
        |
        v
Application executes the selected calculation
        |
        v
Calculation result is returned to Gemini
        |
        v
Gemini generates the final response
        |
        v
Response is returned to the browser

I use Google's @google/genai SDK to communicate with Gemini.

When the user submits a question, the backend validates the input and sends it to Gemini along with the available function declarations. Gemini can then request one of the supported calculations.

The backend identifies the requested function, executes the corresponding logic, and sends the result back to Gemini. The final response is then returned to the browser as JSON.

One detail worth noting is that my current implementation handles the first function call returned by Gemini. It doesn't repeatedly execute multiple function calls in a loop.

Defining the available functions

Before Gemini can request a function, it needs to know which functions are available and what each one does.

I defined four calculation functions:

  • ctc_calculator — calculates estimated monthly take-home salary from annual CTC.
  • calculate_hra_exemption — calculates the eligible HRA exemption.
  • calculate_income_tax — calculates income tax using the selected tax regime and relevant inputs.
  • calculate_pf — calculates provident fund contributions based on the supplied salary details.

Each function declaration contains a name, description, and parameter schema.

For example, here's a simplified version of the salary calculator declaration:

const ctcCalculator = {
  type: "function",
  name: "ctc_calculator",
  description:
    "Calculates the monthly in-hand salary from the given annual CTC.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      ctc: {
        type: Type.NUMBER,
        description: "Annual CTC in Indian rupees.",
      },
    },
    required: ["ctc"],
  },
};

This tells Gemini that the function calculates monthly take-home salary and requires an annual CTC value.

The schema helps the model generate structured arguments instead of returning an unstructured explanation.

Clear function names and descriptions are important. If the available functions have vague or overlapping descriptions, the model may have difficulty selecting the appropriate one.

The declaration itself doesn't contain the calculation logic. It describes the function to Gemini; the application is responsible for executing it.

Letting Gemini choose a function

When sending a request to Gemini, I provide the user's question, the available function declarations, and the system instructions that guide the assistant.

const apiKey = "xxxx";
const apiClient = new GoogleGenAI({ apiKey });

const response = await apiClient.interactions.create({
  model: "gemini-3.8-flash",
  input: "My CTC is ₹20 LPA. What will be my monthly take-home salary?",
  tools: [ctcCalculator],
});

This configuration asks Gemini to select a function rather than respond only with ordinary text for that interaction.

For the salary question, Gemini might return a function call similar to this:

{
  "name": "ctc_calculator",
  "arguments": {
    "ctc": 2000000
  }
}

This is an illustrative example of the function call, not an actual captured response.

Gemini has identified the calculation it wants to perform and supplied the required argument. At this stage, the calculation hasn't happened yet.

My backend receives the function call and decides how to execute it.

Executing the requested function

The backend maps the requested function name to the corresponding calculation logic.

For example, the salary calculation uses the supplied CTC to invoke the existing salary calculator. Other branches handle HRA exemption, income tax, and PF calculations.

A simplified example looks like this:

const functionCall = response.steps.find(
  (step) => step.type === "function_call",
);

if (functionCall.name === "ctc_calculator") {
  const args = functionCall.arguments ?? {};
  const ctc = Number(args.ctc ?? 0);

  const result =
    Number.isFinite(ctc) && ctc > 0
      ? calculateIndiaSalary({
          ctc,
          regime: "new",
          bonusAmount: 0,
        })
      : { error: "Invalid CTC." };
}

This example illustrates the salary calculation branch. The actual implementation has separate branches for the other supported functions.

One benefit of this approach is that I can reuse existing business logic rather than duplicate calculation formulas inside the prompt or ask the LLM to perform the arithmetic.

The application remains responsible for the calculations, while Gemini handles natural-language understanding and response generation.

A note about validation

Function declarations help Gemini generate arguments in the expected format, but they don't replace server-side validation.

In my current implementation, the CTC branch checks whether the converted amount is finite and greater than zero. The other calculation branches don't all have an equivalent, comprehensive validation layer.

This is an important distinction: a schema provided to an LLM guides its output, but the backend still needs to validate inputs before using them in business logic.

Returning the result to Gemini

After executing a function, the backend has the calculated result. The next step is to send that result back to Gemini.

Conceptually, the interaction looks like this:

Gemini requests:
ctc_calculator({ ctc: 2000000 })

Application executes:
calculateIndiaSalary(...)

Application returns:
The calculation result

Gemini generates:
A natural-language explanation of the result

In the implementation, I send a function_result input containing the function name, the original call ID, and the serialized calculation result.

The follow-up interaction also references the preceding interaction ID. This connects the tool result to the function call that requested it.

A simplified example is:

const finalResult = await apiClient.interactions.create(
  {
    type: "function_result",
    name: functionCall.name,
    call_id: functionCall.id,
    result: JSON.stringify(computedToolResult, null, 2),
  },
  previous_interaction_id : response.id,
  tools,
  system_instruction,
);

The follow-up request allows Gemini to use the calculation result to formulate its final response.

If the follow-up response doesn't contain text, my implementation falls back to returning the serialized calculation result.

This separation is useful because the arithmetic comes from application code, while the LLM makes the result easier for the user to understand.

What I learned

Implementing function calling helped me understand that connecting an LLM to an application involves more than sending a prompt and displaying the response.

The important parts are defining useful functions, describing their responsibilities clearly, validating arguments, executing the correct business logic, and returning the results in the format expected by the model.

It also reinforced a principle I want to follow when building AI applications:

Use the LLM to understand requests and generate flexible responses. Use application code for business rules that require predictable execution.

Function calling provides the bridge between these two responsibilities.

My current implementation is intentionally limited to four calculation functions. As I extend it, I'd like to strengthen argument validation, improve unsupported-call handling, and explore multi-step tool execution.

Final thoughts

Function calling made my AI Assist feature more useful by allowing it to work with actual application capabilities instead of relying entirely on generated text.

The model identifies a suitable calculation and supplies structured arguments. The backend executes the corresponding function and returns its result to Gemini, which then generates a response for the user.

This is a useful building block for more capable AI assistants and agents, but it also demonstrates why application-side validation and execution control remain important.

For me, the biggest takeaway is simple: an LLM becomes more useful when it can work with real application logic, rather than trying to replace that logic with generated answers.