$AI Income Hub
HomeAI AutomationBuilding and Deploying Production-Ready AI Agents
AI Automation

Building and Deploying Production-Ready AI Agents

A technical guide on building a functional AI agent using PHP and Gemini Flash, deployed on affordable shared hosting for production use.

Build a Production-Ready AI Agent for Real-World Automation on a Low-Cost Hosting Stack

Building and Deploying Production-Ready AI Agents

Most AI agent tutorials rely on complex, expensive infrastructure that’s out of reach for independent developers, freelancers, and small business owners looking to implement practical automation. This guide walks you through building a fully functional, production-grade AI Agent using tools you likely already have access to: PHP, MySQL, Gemini Flash, and standard cPanel shared hosting. Unlike flashy demos that fall apart in real use, this stack is built for reliability, scalability, and low overhead, making it ideal for both client projects and your own automation workflows.

By the end of this guide, you’ll understand how to structure an agent loop, implement tool calling, store conversation memory, expose a public API endpoint, and deploy the system on shared hosting. You’ll also learn how to turn this skill into a revenue stream through freelance services and digital product sales.

Prerequisites

Before you start building, confirm you have access to the following tools and knowledge:

  • PHP 8.1 or newer installed on your hosting environment
  • Active MySQL database access (available
  • cURL enabled in your PHP configuration (required to call the Gemini API)
  • A Gemini API key from Google AI Studio (Gemini Flash is free for low-volume use, making it cost-effective for testing and small client projects)
  • Basic familiarity with PHP arrays, JSON parsing, and SQL queries
  • Access to cPanel and phpMyAdmin for database management and file uploads

You do not need a dedicated application server or cloud hosting account. The entire project runs on ordinary shared hosting, stored in a folder under your public_html directory.

Core Architecture of the AI Agent System

The system is built around five interconnected components that work together to deliver intelligent, tool-using automation:

  • A public API endpoint that receives user requests and session identifiers
  • A core agent loop that manages conversation flow and coordinates with the LLM
  • A tool registry that defines available functions and their required parameters
  • Custom PHP tools that execute real-world actions (saving data, sending emails, pulling external data, etc.)
  • A MySQL database that stores full conversation history for context retention across requests

The workflow is straightforward. When a user sends a message to the endpoint, the agent loads any existing conversation history for that user’s session, then sends the full context to Gemini Flash along with a list of available tools. Gemini Flash evaluates the request: if it can answer directly, it returns a text response. If the request requires an action, it returns a structured function call with the tool name and required arguments.

PHP executes the matching tool from the registry, adds the tool result to the conversation history, and sends the updated context back to Gemini Flash. The model can then call additional tools or return a final answer to the user. This repeated cycle of reasoning, tool execution, and context updating is what defines the system as an AI Agent, rather than a basic static chatbot.

Project File Structure

Start by creating a folder named agent inside your public_html directory. Your final file structure will look like this:

  • public_html/agent/index.php: Public API endpoint that accepts incoming user requests
  • public_html/agent/agent.php: Core agent loop that manages conversation flow and Gemini interactions
  • public_html/agent/gemini.php: Wrapper for all Gemini Flash API calls and request formatting
  • public_html/agent/db.php: Secure MySQL database connection handler
  • public_html/agent/memory.php: Functions to load and save conversation history to MySQL
  • public_html/agent/tool_registry.php: Maps tool names to their PHP implementations and parameter schemas
  • public_html/agent/tools/: Folder containing individual PHP scripts for each custom tool

Step 1: Set Up Your MySQL Database

CREATE TABLE conversations (
 id INT AUTO_INCREMENT PRIMARY KEY,
 session_id VARCHAR(255) NOT NULL,
 role ENUM('user', 'assistant', 'tool') NOT NULL,
 content TEXT,
 tool_call JSON NULL,
 tool_result JSON NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 INDEX (session_id)
);

You can also create a separate notes table if you plan to build a save_note tool for persistent storage of user data across sessions.

Step 2: Connect PHP to MySQL

Build your db.php file using PDO for secure, SQL-injection-resistant database connections, a core best practice for any production software development project. Include your database credentials, set the connection charset to utf8mb4 to support emojis and special characters, and add error handling to catch connection issues gracefully.

Step 3: Integrate Gemini Flash for Reasoning and Function Calling

Gemini Flash is the ideal LLM for this use case: it is fast, low-cost, and has native support for structured function calling, which eliminates the need for complex prompt engineering to extract tool parameters. Build your gemini.php file to wrap the Gemini API endpoint, include your API key, and format request payloads that include the full conversation history, system prompt, and tool definitions from your registry.

When formatting the request, pass the tool definitions as a structured JSON array that matches the schema in your tool registry. This tells Gemini Flash exactly what tools are available, what parameters they require, and what they do, so it can make accurate decisions about when to call a tool.

Step 4: Build Your Tool Registry and Custom Tools

Your tool_registry.php file is a simple associative array that maps tool names to their file paths, parameter schemas, and descriptions. For example:

return [
 'save_note' => [
 'file' => 'tools/save_note.php',
 'description' => 'Save a user note to the database for later retrieval',
 'parameters' => [
 'content' => ['type' => 'string', 'required' => true, 'description' => 'The text content of the note']
 ]
 ],
 'get_weather' => [
 'file' => 'tools/get_weather.php',
 'description' => 'Fetch current weather data for a given city',
 'parameters' => [
 'city' => ['type' => 'string', 'required' => true, 'description' => 'Name of the city to check weather for']
 ]
 ]
];

Step 5: Add Conversation Memory with MySQL

Build your memory.php file with two core functions: one to load all conversation messages for a given session_id, ordered by creation date, and one to save new messages (user inputs, assistant responses, tool calls, and tool results) to the database. This persistent memory is what allows the agent to maintain context across multiple requests: for example, if a user asks the agent to draft an email on Monday, then follows up with edits on Wednesday, the agent will remember the original draft.

Step 6: Build the Core Agent Loop

The agent.php file is the heart of your AI Agent. The loop follows these steps:

  1. Load the incoming user message and session ID from the request
  2. Pull existing conversation history for the session from MySQL
  3. Add the new user message to the conversation history
  4. Send the full conversation context and tool registry to Gemini Flash
  5. Check the model’s response: if it is a text answer, add it to the history, save to MySQL, and return it to the user
  6. If the response is a function call, look up the matching tool in the registry, execute the PHP tool, add the tool result to the conversation, and send the updated context back to Gemini Flash
  7. Repeat steps 4-6 until Gemini Flash returns a final text response with no additional tool calls

This loop enables complex, multi-step automation: the agent can chain multiple tool calls together to complete tasks like researching a vendor, adding their details to a CRM, and sending a notification to your procurement team, all without manual input.

Step 7: Expose the Public API Endpoint

Your index.php file acts as the public interface for the agent. It accepts POST requests with two required parameters: message (the user’s input) and session_id (a unique identifier for the user or conversation thread). Add basic input validation to reject empty messages or invalid session IDs, then pass the data to the agent loop and return the final response as JSON.

For production use, add simple API key authentication to the endpoint to ensure only authorized users or integrated tools can access the agent. You can connect this endpoint to third-party tools like Slack, WordPress, or custom dashboards, so users can interact with the agent from their existing workflows.

Step 8: Deploy on cPanel Shared Hosting

Deploying the agent takes less than 10 minutes with standard cPanel tools:

  • Upload the entire agent folder to your public_html directory
  • Create your MySQL database and user in cPanel, then import the conversation table schema
  • Update db.php with your new database credentials, and gemini.php with your Gemini API key
  • Set file permissions to 755 for folders and 644 for files to ensure the web server can read and execute the scripts
  • Test the endpoint by sending a POST request with a tool like Postman or curl to https://yourdomain.com/agent/index.php

Because this stack runs on standard shared hosting, you avoid the cost and complexity of managing a VPS or cloud server. You can host multiple client agents on a single $5-$10/month hosting plan, keeping overhead extremely low.

Step 9: Test and Harden for Production

Run through test cases to confirm the agent works as expected: send a simple question that requires no tools, send a request that triggers a tool call, and send a follow-up message to confirm the agent retains context. For production use, add the following hardening steps:

  • Sanitize all user inputs to prevent injection attacks
  • Add rate limiting to the API endpoint to block abuse
  • Implement error logging for Gemini API failures and tool execution errors
  • Add regular automated backups of your MySQL database
  • Cache frequent tool call results to reduce API costs and speed up response times

Monetize Your AI Agent Automation Skills

This stack is highly marketable for freelancers and software developers looking to generate income with AI automation:

  • Freelance custom builds: Offer tailored AI agent solutions for small businesses on platforms like Upwork and Fiverr. For example, build a customer support agent that answers FAQs, saves support tickets to a database, and sends alerts to your client’s team. Custom builds typically sell for $500-$2,000 per project, with $100-$500 monthly retainers for maintenance and updates.
  • Niche digital products: Build pre-built agents for specific industries (real estate, e-commerce, healthcare) and sell them as white-label solutions on Gumroad or your own website for $50-$200 per license.
  • Automation consulting: Help businesses integrate these agents into their existing workflows, charging hourly rates of $75-$200 for setup, training, and customization.

Conclusion

Building a production-ready AI Agent does not require expensive infrastructure or cutting-edge tools. With PHP, MySQL, Gemini Flash, and standard shared hosting, you can build reliable, scalable automation solutions that solve real business problems. The low overhead of this stack makes it perfect for freelancers looking to offer high-margin AI services, or developers building niche automation products for global markets. Start with a simple tool like a note-saving agent, then expand its functionality to meet the needs of your clients or your own workflows.

#AI agents#PHP#Gemini Flash#Deployment#Production Ready