Um bot de suporte que inventa saldos de conta não é apenas inútil em um banco digital. É perigoso. Conversas financeiras exigem números exatos, beneficiários verificados e uma trilha de auditoria para cada afirmação. Modelos de linguagem de grande escala são excelentes em conversação, mas eles alucinam. Quando um usuário pergunta: “Quanto resta na minha conta?”, o modelo deve recorrer a um banco de dados, não à imaginação. É exatamente isso que o function calling impõe, e é o núcleo deste projeto.
O Gemma 4 do Google oferece aos desenvolvedores um modelo capaz de 31 bilhões de parâmetros que pode seguir instruções complexas e manter um diálogo natural, inclusive em dialetos regionais. Combinado com o Google AI Studio, ele se torna um ambiente de prototipagem rápida onde você pode definir ferramentas, testar casos de borda e exportar JavaScript funcional antes mesmo de tocar em um servidor. O objetivo aqui é um agente de suporte fintech que verifica saldos de conta, acompanha o status de transações e paga contas. Crucialmente, ele responde em Pidgin nigeriano quando o usuário o faz, combinando o tom sem nunca improvisar fatos financeiros.
Por que o Function Calling é importante para bots financeiros
Sem o function calling, um modelo de linguagem trata cada pergunta como um exercício de escrita criativa. Peça a ele um saldo e ele pode inventar um valor com aparência plausível, extraído de padrões em seus dados de treinamento. Esse modo de falha é inaceitável quando dinheiro real está envolvido.
O function calling inverte o fluxo. O trabalho do modelo não é saber o saldo. Seu trabalho é reconhecer a intenção, escolher a ferramenta correta e extrair os parâmetros. Quando um usuário escreve “Verificar meu saldo”, o Gemma 4 emite uma solicitação JSON estruturada — algo como uma chamada para get_balance com um account_id. Seu backend executa essa chamada contra o sistema bancário central, obtém o valor real e o envia de volta para a conversa. Só então o modelo gera a frase voltada para o usuário. Cada resposta vem de uma chamada de ferramenta para um backend. Como o modelo é limitado por uma lógica externa, as alucinações param no limite da API.
Esse padrão também cria trilhas de auditoria claras. Cada solicitação de ferramenta e seu resultado correspondente são registrados no histórico de mensagens. Reguladores e equipes de risco podem inspecionar exatamente quando um saldo foi verificado e qual número o usuário recebeu.
Projetando o Agente no Google AI Studio
O fluxo de trabalho começa dentro do Google AI Studio. Selecione gemma-4-31b-it, a variante ajustada para instruções (instruct-tuned) otimizada para diálogo e seguimento de instruções.
Em seguida, escreva instruções de sistema que estabeleçam limites rígidos. Para um banco digital, o tom deve ser profissional, direto e calmo. Mas as instruções devem ir além. Diga explicitamente ao modelo que ele nunca estima dados de conta, nunca assume um status de transação e nunca conclui o pagamento de uma conta sem confirmar o resultado da ferramenta. Se o usuário escrever em Pidgin nigeriano, o modelo deve responder em Pidgin nigeriano. Se o usuário mudar para o inglês, o modelo o segue. O system prompt é onde você codifica a política de confiança e segurança em linguagem clara.
Então, defina os esquemas das ferramentas (tool schemas). Pense neles como contratos entre o modelo e o seu backend. Você precisará de pelo menos três:
get_balance
Parâmetros:account_id(string, obrigatório)
Retorna: saldo atual e moeda.get_transaction_status
Parâmetros:transaction_reference(string, obrigatório)
Retorna: status como pendente, concluído ou falhou, além de um timestamp.pay_bill
Parâmetros:biller_code(string, obrigatório),amount(number, obrigatório),account_pin(string, opcional dependendo do seu fluxo)
Retorna: referência de confirmação ou mensagem de erro.
Cada esquema usa um formato JSON padrão descrevendo o nome da função, a descrição e as propriedades dos parâmetros. Os campos de descrição são extremamente importantes. Escreva-os de forma que o modelo entenda quando invocar cada ferramenta. Descrições ambíguas levam à seleção errada da ferramenta, portanto, seja específico: “Use get_balance quando o usuário quiser saber o saldo atual da conta. Não o use para o histórico de transações.”
Prototipagem no Navegador
Antes de escrever uma única rota Express, teste todo o fluxo de conversa dentro do painel de chat do AI Studio. Isso economiza dias de retrabalho no backend. Digite uma consulta em Pidgin nigeriano: “Wetin remain inside my account?” Observe se o Gemma 4 emite corretamente uma chamada get_balance ou se ele tenta responder com base nos dados de treinamento. Se ele errar os parâmetros — talvez usando account_number em vez de account_id — você corrige a descrição do esquema ali mesmo.
Test the failure modes too. Ask for a transaction status without providing a reference number. A well-instructed model should either ask the user for the missing parameter or call the tool with what it has and let the backend return a validation error. You want to see these behaviors in the sandbox, not in production.
Once the prompts and schemas behave correctly, export the JavaScript code. AI Studio generates a clean snippet that structures the API request with your system prompt, user message, and tool definitions. This becomes the foundation of your backend logic.
Wiring Up the Express Backend
Take the exported code and drop it into an Express application. The architecture is straightforward, but the execution loop is the critical piece.
Set up a POST endpoint—perhaps /chat—that accepts the user’s message and any session history. Forward these to the Gemma 4 endpoint, which you can hit via an OpenAI-compatible API or Google’s own inference endpoint depending on your hosting choice.
The response from the model falls into one of two categories. Either it is a final text message, or it contains a tool_call requesting data. When you receive a tool call, execute the corresponding function against your backend. Query the database for the balance. Hit the payment processor for the bill status. Append the tool result to the conversation history as a new message with the role tool, and send the entire updated array back to Gemma 4.
Repeat this loop until the model returns a final text answer. That answer will be grounded in the real data you supplied. Express makes this easy to coordinate because each pass through the loop is just another HTTP request, and you can async/await the tool execution cleanly.
During early development, back these tool calls with mock data. A simple JavaScript object mapping sample account IDs to balances is enough to prove the loop works. The point is to validate the interaction pattern before integrating with brittle third-party banking APIs.
From Prototype to Production
A working prototype is not production banking infrastructure, but the path from one to the other is clear.
Replace the mock data with real core banking APIs. Connect your get_balance tool to the ledger system over REST or gRPC. Hook pay_bill into your actual payment switch. When you do this, you do not need to change the model or the conversation logic; you only swap the implementation of the tool handlers.
Add Redis for session management. Conversational state in banking is sensitive and regulated. You need to store message histories securely, expire them after a set timeout, and ensure that a user’s session cannot leak across requests. Redis handles this with TTL policies and fast key lookups.
When traffic grows, moveInference to vLLM. AI Studio is excellent for prototyping, but self-hosted inference with vLLM on GPU clusters gives you control over latency, batching, and cost at scale. Gemma 4 runs efficiently under vLLM, and the tool-calling behavior remains identical.
The Real Takeaway
Building a trustworthy fintech agent is less about model size and more about architectural constraints. Gemma 4 provides enough reasoning power to parse code-switched Nigerian Pidgin and route complex intents, but the safety comes from the tool loop. Every balance is fetched live. Every bill payment is confirmed by an external system. Nothing is invented.
Start in the browser with AI Studio, harden the logic in an Express loop, and swap in real banking infrastructure once the conversation flows are bulletproof. That is how you ship a bot people can actually trust with their money.
Source: Building a Full Gemma 4 Google AI Studio Project: A Fintech Support Agent
Optional learning community: GyaanSetu AI on Telegram
