<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hasanur Rahman Shahin</title>
    <description>The latest articles on DEV Community by Hasanur Rahman Shahin (@mdhrshahin).</description>
    <link>https://dev.to/mdhrshahin</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F682012%2F0e620967-79ba-44bd-9f53-fa9f201b7348.jpeg</url>
      <title>DEV Community: Hasanur Rahman Shahin</title>
      <link>https://dev.to/mdhrshahin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mdhrshahin"/>
    <language>en</language>
    <item>
      <title>AI-Powered Chat System with Multi-Project Support With Laravel</title>
      <dc:creator>Hasanur Rahman Shahin</dc:creator>
      <pubDate>Tue, 11 Feb 2025 07:16:58 +0000</pubDate>
      <link>https://dev.to/mdhrshahin/ai-powered-chat-system-with-multi-project-support-with-laravel-4h95</link>
      <guid>https://dev.to/mdhrshahin/ai-powered-chat-system-with-multi-project-support-with-laravel-4h95</guid>
      <description>&lt;p&gt;This system enables an AI chatbot that &lt;strong&gt;checks the database first&lt;/strong&gt; before calling GPT-4o. It supports &lt;strong&gt;multiple projects&lt;/strong&gt;, storing AI responses separately for each project. Additionally, AI-generated responses are &lt;strong&gt;saved in the background&lt;/strong&gt; to improve future interactions.&lt;/p&gt;




&lt;h2&gt;
  
  
  Features
&lt;/h2&gt;

&lt;p&gt;✅ &lt;em&gt;Database First:&lt;/em&gt; If a response is found with &lt;em&gt;80% similarity&lt;/em&gt;, return it immediately.&lt;br&gt;&lt;br&gt;
✅ &lt;em&gt;GPT-4o Fallback:&lt;/em&gt; If no match is found, call GPT-4o and return the response.&lt;br&gt;&lt;br&gt;
✅ &lt;em&gt;Background Job:&lt;/em&gt; Store new AI responses in the background using Laravel Queues.&lt;br&gt;&lt;br&gt;
✅ &lt;em&gt;Multi-Project Support:&lt;/em&gt; Each AI response is linked to a specific project.&lt;br&gt;&lt;br&gt;
✅ &lt;em&gt;Rate Limiting:&lt;/em&gt; Prevents spam and abuse.&lt;/p&gt;


&lt;h1&gt;
  
  
  Database Design
&lt;/h1&gt;
&lt;h2&gt;
  
  
  &lt;code&gt;conversations&lt;/code&gt; Table (Stores Trained AI Data)
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Column&lt;/th&gt;
&lt;th&gt;Type&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;id&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;bigint&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Primary Key&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;project&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;string&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Project name&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;prompt&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;text&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;User query (Unique)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;response&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;text&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;AI-generated response&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;created_at&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timestamp&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Timestamp&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;code&gt;chat_logs&lt;/code&gt; Table (Logs Each Chat Interaction)
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Column&lt;/th&gt;
&lt;th&gt;Type&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;id&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;bigint&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Primary Key&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;project&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;string&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Project name&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;prompt&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;text&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;User query&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;response&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;text&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Response sent to user&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;source&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;enum(database, AI)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Whether response came from DB or AI&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;created_at&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timestamp&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Timestamp&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;


&lt;h1&gt;
  
  
  API Implementation
&lt;/h1&gt;
&lt;h3&gt;
  
  
  Request Format
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{     "project": "job_portal",     "prompt": "How to create a job listing?" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Response (From Database)
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{     "source": "database",     "response": "You can create a job listing by..." }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Response (From GPT-4o, If No Match)
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{     "source": "AI",     "response": "To create a job listing, follow these steps..." }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Backend Implementation
&lt;/h1&gt;
&lt;h2&gt;
  
  
  🔹 AIController.php
&lt;/h2&gt;

&lt;p&gt;Handles &lt;strong&gt;chat request, database check, GPT-4o API call&lt;/strong&gt;, and &lt;strong&gt;background job dispatch&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Conversation;
use App\Models\ChatLog;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use App\Jobs\StoreTrainedData;

class AIController extends Controller
{
    public function chat(Request $request)
    {
        $request-&amp;gt;validate([
            'project' =&amp;gt; 'required|string',
            'prompt' =&amp;gt; 'required|string'
        ]);

        $project = $request-&amp;gt;input('project');
        $prompt = $request-&amp;gt;input('prompt');

        // **Rate Limiting**
        if (RateLimiter::tooManyAttempts('chat:' . $request-&amp;gt;ip(), 10)) {
            return response()-&amp;gt;json([
                'error' =&amp;gt; 'Too many requests. Please wait a while before trying again.'
            ], 429);
        }
        RateLimiter::hit('chat:' . $request-&amp;gt;ip(), 60);

        // **Check Database for Similar Prompt**
        $similarConversation = $this-&amp;gt;findSimilarPrompt($project, $prompt);

        if ($similarConversation) {
            ChatLog::create([
                'project' =&amp;gt; $project,
                'prompt' =&amp;gt; $prompt,
                'response' =&amp;gt; $similarConversation-&amp;gt;response,
                'source' =&amp;gt; 'database'
            ]);

            return response()-&amp;gt;json([
                'source' =&amp;gt; 'database',
                'response' =&amp;gt; $similarConversation-&amp;gt;response
            ]);
        }

        // **Call GPT-4o**
        $aiResponse = $this-&amp;gt;callGPT4o($prompt);

        // **Save Response in Background**
        StoreTrainedData::dispatch($project, $prompt, $aiResponse)-&amp;gt;onQueue('default');

        // **Log Chat Response**
        ChatLog::create([
            'project' =&amp;gt; $project,
            'prompt' =&amp;gt; $prompt,
            'response' =&amp;gt; $aiResponse,
            'source' =&amp;gt; 'AI'
        ]);

        return response()-&amp;gt;json([
            'source' =&amp;gt; 'AI',
            'response' =&amp;gt; $aiResponse
        ]);
    }

    private function findSimilarPrompt($project, $prompt)
    {
        $similarPrompts = Conversation::where('project', $project)
            -&amp;gt;whereRaw("MATCH(prompt) AGAINST(? IN NATURAL LANGUAGE MODE)", [$prompt])
            -&amp;gt;get();

        foreach ($similarPrompts as $conv) {
            $similarity = $this-&amp;gt;calculateSimilarity($prompt, $conv-&amp;gt;prompt);
            if ($similarity &amp;gt;= 80) {
                return $conv;
            }
        }
        return null;
    }

    private function calculateSimilarity($input1, $input2)
    {
        similar_text($input1, $input2, $percent);
        return $percent;
    }

    private function callGPT4o($prompt)
    {
        $response = Http::withHeaders([
            'Authorization' =&amp;gt; 'Bearer ' . env('OPENAI_API_KEY'),
        ])-&amp;gt;post('https://api.openai.com/v1/chat/completions', [
            'model' =&amp;gt; 'gpt-4o',
            'messages' =&amp;gt; [["role" =&amp;gt; "user", "content" =&amp;gt; $prompt]],
            'temperature' =&amp;gt; 0.7
        ]);

        return $response-&amp;gt;json()['choices'][0]['message']['content'] ?? 'No response';
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  🔹 StoreTrainedData.php (Background Job)
&lt;/h2&gt;

&lt;p&gt;Stores AI responses &lt;strong&gt;in the background&lt;/strong&gt; after returning the response.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace App\Jobs;

use App\Models\Conversation;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class StoreTrainedData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $project;
    protected $prompt;
    protected $response;

    public function __construct($project, $prompt, $response)
    {
        $this-&amp;gt;project = $project;
        $this-&amp;gt;prompt = $prompt;
        $this-&amp;gt;response = $response;
    }

    public function handle()
    {
        Conversation::create([
            'project' =&amp;gt; $this-&amp;gt;project,
            'prompt' =&amp;gt; $this-&amp;gt;prompt,
            'response' =&amp;gt; $this-&amp;gt;response
        ]);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h1&gt;
  
  
  Setup Laravel Queues
&lt;/h1&gt;

&lt;h2&gt;
  
  
  1. Set Up Database Queue
&lt;/h2&gt;

&lt;p&gt;Run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan queue:table php artisan migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Update &lt;code&gt;.env&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;env&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;QUEUE_CONNECTION=database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start queue worker:&lt;/p&gt;

&lt;p&gt;sh&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan queue:work
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h1&gt;
  
  
  Final Workflow
&lt;/h1&gt;

&lt;p&gt;1️⃣ User sends a &lt;strong&gt;chat request with project name&lt;/strong&gt;.&lt;br&gt;&lt;br&gt;
2️⃣ API &lt;strong&gt;checks the database&lt;/strong&gt; for that project (returns response if found).&lt;br&gt;&lt;br&gt;
3️⃣ If &lt;strong&gt;no match&lt;/strong&gt;, GPT-4o is called, and the &lt;strong&gt;response is sent immediately&lt;/strong&gt;.&lt;br&gt;&lt;br&gt;
4️⃣ The &lt;strong&gt;response is saved in the background&lt;/strong&gt; for future use.&lt;br&gt;&lt;br&gt;
5️⃣ Future queries for that &lt;strong&gt;project&lt;/strong&gt; are answered from the database.&lt;/p&gt;




&lt;h1&gt;
  
  
  Benefits
&lt;/h1&gt;

&lt;p&gt;✅ &lt;strong&gt;Faster Responses&lt;/strong&gt; (Database First, GPT-4o Second)&lt;br&gt;&lt;br&gt;
✅ &lt;strong&gt;Project-Based Data Storage&lt;/strong&gt; (Multiple Projects Supported)&lt;br&gt;&lt;br&gt;
✅ &lt;strong&gt;Background Processing&lt;/strong&gt; (No User Delay)&lt;br&gt;&lt;br&gt;
✅ &lt;strong&gt;Scalable&lt;/strong&gt; (Handles Large Datasets Efficiently)&lt;br&gt;&lt;br&gt;
✅ &lt;strong&gt;Self-Learning&lt;/strong&gt; (AI Gets Smarter Over Time)&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>ai</category>
    </item>
  </channel>
</rss>
