Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Synapse Chat Laravel Package

arnaudmoncondhuy/synapse-chat

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require arnaudmoncondhuy/synapse-chat:^0.1 arnaudmoncondhuy/synapse-core
    
  2. Register Bundle (config/bundles.php):

    ArnaudMoncondhuy\SynapseChat\SynapseChatBundle::class => ['all' => true],
    
  3. Enable Routes (config/routes.yaml):

    synapse_chat:
        resource: '@SynapseChatBundle/config/routes.yaml'
        prefix: /api
    
  4. Security Configuration (config/packages/security.yaml):

    access_control:
        - { path: ^/api/chat, roles: ROLE_USER }
        - { path: ^/api/csrf, roles: PUBLIC_ACCESS }
    
  5. First Use Case: Embed the chat component in a Twig template:

    {% include '@Synapse/chat/component.html.twig' %}
    

Implementation Patterns

Workflow: Embedding a Chat Widget

  1. Template Integration: Use the provided Twig templates for a full-page chat or embeddable component:

    {% include '@Synapse/chat/component.html.twig' with {
        title: 'Support Chat',
        placeholder: 'Ask me anything...'
    } %}
    
  2. Stimulus Controller: The synapse_chat_controller handles:

    • Form submission via AJAX to /api/chat.
    • Streaming responses via NDJSON/SSE.
    • Real-time tool call display.
    • Error handling (e.g., rate limits, API failures).
  3. API Interaction:

    • Send Message: POST to /api/chat with X-CSRF-Token.
    • Stream Response: Listen for messageReceived and responseComplete events.
    • Cost Estimation: POST to /api/estimate-cost before sending.
  4. Conversation Management: Use the API endpoints to:

    • List conversations: GET /api/conversations.
    • Reset a conversation: POST /api/conversation/reset.
    • Manage memory: POST /api/memory/confirm or POST /api/memory/manual.
  5. Asset Integration: Include assets in your layout:

    {% include '@Synapse/chat/assets.html.twig' %}
    

Integration Tips

  • CSRF Protection: Always include the X-CSRF-Token header for POST requests. For SPAs, fetch the token via GET /api/csrf-token.
  • Authentication: Ensure users are authenticated for chat routes (e.g., via ROLE_USER).
  • Presets: Configure the default preset in config/packages/synapse_chat.yaml:
    synapse_chat:
        default_preset_name: "default"
    
  • Customization: Override Twig templates in templates/bundles/SynapseChat/ to modify UI.

Gotchas and Tips

Pitfalls

  1. CSRF Mismatch:

    • Issue: Missing or invalid X-CSRF-Token header causes 403 errors.
    • Fix: Enable CSRF in config (synapse_chat.api_csrf_enabled: true) and ensure the token is included in requests. For SPAs, fetch the token dynamically:
      const csrfToken = await fetch('/api/csrf-token').then(res => res.text());
      
  2. Streaming Disconnections:

    • Issue: SSE connections may drop due to server timeouts or network issues.
    • Fix: Implement reconnection logic in Stimulus:
      connect() {
          this.streaming = this.connectStreaming();
      }
      
      disconnect() {
          this.streaming?.close();
      }
      
      connectStreaming() {
          const eventSource = new EventSource('/api/chat?stream=true');
          eventSource.onmessage = (e) => this.messageReceived(JSON.parse(e.data));
          eventSource.onerror = () => this.connectStreaming(); // Auto-reconnect
          return eventSource;
      }
      
  3. Token Limits:

    • Issue: Exceeding token limits may truncate responses or fail silently.
    • Fix: Use /api/estimate-cost to check token usage before sending:
      const cost = await fetch('/api/estimate-cost', {
          method: 'POST',
          headers: { 'X-CSRF-Token': csrfToken },
          body: JSON.stringify({ message: userInput })
      }).then(res => res.json());
      if (cost.output_tokens > MAX_ALLOWED) {
          showWarning("Message too long. Try shortening it.");
      }
      
  4. Memory Management:

    • Issue: Unconfirmed memory proposals may clutter the system.
    • Fix: Implement frontend confirmation for ProposeMemoryTool responses:
      messageReceived(chunk) {
          if (chunk.type === 'tool_call' && chunk.tool_use.name === 'ProposeMemoryTool') {
              showMemoryConfirmation(chunk.tool_use.input);
          }
      }
      

Debugging Tips

  1. NDJSON Validation:

    • Use browser dev tools to inspect NDJSON chunks for malformed data. Validate each chunk is a valid JSON object.
  2. Stimulus Events:

    • Log events to debug streaming issues:
      messageReceived(event) {
          console.log('Chunk:', event.detail.chunk);
      }
      
  3. API Logs:

    • Enable debug mode in config/packages/dev/synapse_chat.yaml:
      synapse_chat:
          debug: true
      
    • Check Symfony logs (var/log/dev.log) for API errors.

Extension Points

  1. Custom Templates:

    • Override Twig templates (e.g., @Synapse/chat/component.html.twig) in templates/bundles/SynapseChat/.
  2. Stimulus Extensions:

    • Extend the synapse_chat_controller by adding custom methods:
      static get targets() { return [...super.targets(), 'customTarget']; }
      
  3. API Middleware:

    • Add middleware to /api/chat for custom logic (e.g., logging, rate limiting):
      # config/routes.yaml
      synapse_chat:
          resource: '@SynapseChatBundle/config/routes.yaml'
          prefix: /api
          defaults: { _controller: 'App\Controller\ChatMiddleware::process' }
      
  4. Translation Overrides:

    • Customize translations in translations/synapse_chat.en.yaml:
      synapse:
          chat:
              input_area:
                  placeholder: "Ask your custom question here..."
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware