Plugin Directory

Changeset 3741982


Ignore:
Timestamp:
10/12/2026 03:25:51 PM (6 weeks ago)
Author:
muradbd
Message:

2.8.0 - Citations, usage/budget caps, real streaming, cloud embeddings, insights; remove unused Freemius SDK

Location:
easyit-ai-chat/trunk
Files:
2 added
1 deleted
23 edited

Legend:

Unmodified
Added
Removed
  • easyit-ai-chat/trunk/admin/class-eaic-admin.php

    r3617603 r3741982  
    209209                        $input = array();
    210210                }
     211
     212                // Partial forms (the Knowledge Base page) post only their own fields plus a
     213                // `_passthrough` marker. Run the normal sanitiser, but keep every setting the
     214                // form doesn't own at its current value — otherwise saving that page would blank
     215                // the API keys and untick every checkbox that lives on the Settings page.
     216                if ( ! empty( $input['_passthrough'] ) ) {
     217                        unset( $input['_passthrough'] );
     218                        $owned   = array(
     219                                'rag_enabled', 'rag_embed_provider', 'rag_embed_model', 'rag_chunk_size', 'rag_chunk_overlap',
     220                                'rag_top_k', 'rag_threshold', 'site_index_enabled', 'site_index_post_types', 'citations_enabled',
     221                        );
     222                        $clean   = $this->sanitize_all( $input );
     223                        $current = EAIC_Options::all();
     224                        foreach ( $owned as $key ) {
     225                                if ( array_key_exists( $key, $clean ) ) {
     226                                        $current[ $key ] = $clean[ $key ];
     227                                }
     228                        }
     229                        return $current;
     230                }
     231
     232                return $this->sanitize_all( $input );
     233        }
     234
     235        /**
     236         * Sanitize a complete settings payload (every option falls back to its saved value when absent).
     237         *
     238         * @param array $input Raw input.
     239         * @return array
     240         */
     241        private function sanitize_all( array $input ) {
    211242                $current = EAIC_Options::all();
    212243
    … …  
    331362                        // v2.3.0 — RAG
    332363                        'rag_enabled'                 => ! empty( $input['rag_enabled'] ),
     364                        'rag_embed_provider'          => ( isset( $input['rag_embed_provider'] ) && in_array( $input['rag_embed_provider'], array( 'auto', 'ollama', 'openai', 'gemini' ), true ) )
     365                                                           ? $input['rag_embed_provider'] : $current['rag_embed_provider'],
    333366                        'rag_embed_model'             => isset( $input['rag_embed_model'] )   ? sanitize_text_field( $input['rag_embed_model'] )                                : $current['rag_embed_model'],
    334367                        'rag_chunk_size'              => isset( $input['rag_chunk_size'] )    ? max( 50, min( 2000, absint( $input['rag_chunk_size'] ) ) )                     : $current['rag_chunk_size'],
    … …  
    344377                        'attachments_enabled'             => ! empty( $input['attachments_enabled'] ),
    345378                        'attachments_upload_max_image_mb'  => isset( $input['attachments_upload_max_image_mb'] ) ? max( 1, min( 50, absint( $input['attachments_upload_max_image_mb'] ) ) )  : $current['attachments_upload_max_image_mb'],
     379                        // v2.8.0 — Source citations, usage tracking & budget caps
     380                        'citations_enabled'               => isset( $input['citations_enabled'] )    ? '0' !== (string) $input['citations_enabled']    : $current['citations_enabled'],
     381                        'budget_daily_tokens'             => isset( $input['budget_daily_tokens'] )   ? max( 0, absint( $input['budget_daily_tokens'] ) )   : $current['budget_daily_tokens'],
     382                        'budget_monthly_tokens'           => isset( $input['budget_monthly_tokens'] ) ? max( 0, absint( $input['budget_monthly_tokens'] ) ) : $current['budget_monthly_tokens'],
     383                        'budget_monthly_usd'              => isset( $input['budget_monthly_usd'] )    ? max( 0.0, round( (float) $input['budget_monthly_usd'], 2 ) ) : $current['budget_monthly_usd'],
     384                        'budget_message'                  => isset( $input['budget_message'] )        ? sanitize_text_field( $input['budget_message'] )     : $current['budget_message'],
     385                        'digest_enabled'                  => ! empty( $input['digest_enabled'] ),
     386                        'digest_email'                    => isset( $input['digest_email'] )       ? sanitize_email( $input['digest_email'] )       : $current['digest_email'],
     387                        'lead_main_enabled'               => ! empty( $input['lead_main_enabled'] ),
     388                        'lead_notify_enabled'             => ! empty( $input['lead_notify_enabled'] ),
     389                        'lead_notify_email'               => isset( $input['lead_notify_email'] )  ? sanitize_email( $input['lead_notify_email'] )  : $current['lead_notify_email'],
     390                        'budget_alert_enabled'            => isset( $input['budget_alert_enabled'] ) ? '0' !== (string) $input['budget_alert_enabled'] : $current['budget_alert_enabled'],
     391                        'usage_price_overrides'           => isset( $input['usage_price_overrides'] ) ? sanitize_textarea_field( $input['usage_price_overrides'] ) : $current['usage_price_overrides'],
    346392                        'attachments_upload_max_doc_mb'    => isset( $input['attachments_upload_max_doc_mb'] )   ? max( 1, min( 100, absint( $input['attachments_upload_max_doc_mb'] ) ) )   : $current['attachments_upload_max_doc_mb'],
    347393                );
    … …  
    626672                $eaic_daily    = EAIC_DB::get_messages_per_day( 7 );
    627673                $eaic_feedback = EAIC_DB::get_feedback_stats();
     674                $eaic_usage    = EAIC_Usage::totals();
     675                $eaic_usage_by = EAIC_Usage::month_breakdown();
     676                $eaic_usage_14 = EAIC_Usage::tokens_per_day( 14 );
     677                $eaic_gaps       = EAIC_Insights::top_gaps( 15 );
     678                $eaic_downvoted  = EAIC_Insights::downvoted( 8 );
     679                $eaic_digest_on  = (bool) EAIC_Options::get( 'digest_enabled', false );
    628680
    629681                // WooCommerce bots (merged in from Pro) — only present when those tables exist.
  • easyit-ai-chat/trunk/admin/views/analytics-page.php

    r3617353 r3741982  
    8383                        <div class="eaic-stat-label"><?php esc_html_e( 'Not helpful ratings', 'easyit-ai-chat' ); ?></div>
    8484                </div>
     85        </div>
     86
     87        <?php if ( ! $eaic_digest_on ) : ?>
     88        <div class="notice notice-info inline" style="margin:12px 0">
     89                <p>
     90                        <strong><?php esc_html_e( 'Get this report in your inbox.', 'easyit-ai-chat' ); ?></strong>
     91                        <?php esc_html_e( 'A short weekly summary: questions answered, AI cost, new leads and what the bot could not answer.', 'easyit-ai-chat' ); ?>
     92                        <a class="button button-small" style="margin-left:8px" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=eaic_enable_digest' ), 'eaic_enable_digest' ) ); ?>"><?php esc_html_e( 'Turn on weekly summary', 'easyit-ai-chat' ); ?></a>
     93                </p>
     94        </div>
     95        <?php endif; ?>
     96
     97        <!-- AI usage & estimated cost -->
     98        <?php
     99        $eaic_day_tokens   = $eaic_usage['day']['input'] + $eaic_usage['day']['output'];
     100        $eaic_month_tokens = $eaic_usage['month']['input'] + $eaic_usage['month']['output'];
     101        $eaic_cap_daily    = (int) EAIC_Options::get( 'budget_daily_tokens', 0 );
     102        $eaic_cap_monthly  = (int) EAIC_Options::get( 'budget_monthly_tokens', 0 );
     103        $eaic_cap_usd      = (float) EAIC_Options::get( 'budget_monthly_usd', 0 );
     104        $eaic_usage_max    = $eaic_usage_14 ? max( array_values( $eaic_usage_14 ) ) : 0;
     105        ?>
     106        <div class="eaic-stats-grid">
     107                <div class="eaic-stat-card">
     108                        <div class="eaic-stat-icon">🔤</div>
     109                        <div class="eaic-stat-number"><?php echo esc_html( number_format_i18n( $eaic_day_tokens ) ); ?></div>
     110                        <div class="eaic-stat-label">
     111                                <?php esc_html_e( 'Tokens Today', 'easyit-ai-chat' ); ?>
     112                                <?php if ( $eaic_cap_daily > 0 ) : ?>
     113                                        <br><small><?php /* translators: %s: configured daily token limit */ echo esc_html( sprintf( __( 'limit %s', 'easyit-ai-chat' ), number_format_i18n( $eaic_cap_daily ) ) ); ?></small>
     114                                <?php endif; ?>
     115                        </div>
     116                </div>
     117                <div class="eaic-stat-card">
     118                        <div class="eaic-stat-icon">📆</div>
     119                        <div class="eaic-stat-number"><?php echo esc_html( number_format_i18n( $eaic_month_tokens ) ); ?></div>
     120                        <div class="eaic-stat-label">
     121                                <?php esc_html_e( 'Tokens This Month', 'easyit-ai-chat' ); ?>
     122                                <?php if ( $eaic_cap_monthly > 0 ) : ?>
     123                                        <br><small><?php /* translators: %s: configured monthly token limit */ echo esc_html( sprintf( __( 'limit %s', 'easyit-ai-chat' ), number_format_i18n( $eaic_cap_monthly ) ) ); ?></small>
     124                                <?php endif; ?>
     125                        </div>
     126                </div>
     127                <div class="eaic-stat-card">
     128                        <div class="eaic-stat-icon">💵</div>
     129                        <div class="eaic-stat-number">$<?php echo esc_html( number_format_i18n( $eaic_usage['month']['cost'], 2 ) ); ?></div>
     130                        <div class="eaic-stat-label">
     131                                <?php esc_html_e( 'Est. Cost This Month', 'easyit-ai-chat' ); ?>
     132                                <?php if ( $eaic_cap_usd > 0 ) : ?>
     133                                        <br><small><?php /* translators: %s: configured monthly cost limit in USD */ echo esc_html( sprintf( __( 'limit $%s', 'easyit-ai-chat' ), number_format_i18n( $eaic_cap_usd, 2 ) ) ); ?></small>
     134                                <?php endif; ?>
     135                        </div>
     136                </div>
     137                <div class="eaic-stat-card">
     138                        <div class="eaic-stat-icon">🔁</div>
     139                        <div class="eaic-stat-number"><?php echo esc_html( number_format_i18n( $eaic_usage['month']['requests'] ) ); ?></div>
     140                        <div class="eaic-stat-label"><?php esc_html_e( 'AI Requests This Month', 'easyit-ai-chat' ); ?></div>
     141                </div>
     142        </div>
     143
     144        <div class="eaic-card">
     145                <div class="eaic-card-title"><span class="icon">💰</span> <?php esc_html_e( 'AI Usage — This Month', 'easyit-ai-chat' ); ?></div>
     146                <?php if ( empty( $eaic_usage_by ) ) : ?>
     147                        <p class="eaic-no-data"><?php esc_html_e( 'No AI usage recorded yet. It appears here after the first chat message.', 'easyit-ai-chat' ); ?></p>
     148                <?php else : ?>
     149                        <?php if ( $eaic_usage_max > 0 ) : ?>
     150                        <div class="eaic-chart" style="margin-bottom:16px">
     151                                <?php foreach ( $eaic_usage_14 as $eaic_u_date => $eaic_u_tokens ) : ?>
     152                                <div class="eaic-chart-col" title="<?php echo esc_attr( number_format_i18n( $eaic_u_tokens ) ); ?>">
     153                                        <div class="eaic-chart-bar-track">
     154                                                <div class="eaic-chart-bar" style="height:<?php echo esc_attr( (int) round( ( $eaic_u_tokens / $eaic_usage_max ) * 100 ) ); ?>%"></div>
     155                                        </div>
     156                                        <div class="eaic-chart-label"><?php echo esc_html( gmdate( 'j', strtotime( $eaic_u_date ) ) ); ?></div>
     157                                </div>
     158                                <?php endforeach; ?>
     159                        </div>
     160                        <?php endif; ?>
     161                        <table class="eaic-table">
     162                                <thead>
     163                                        <tr>
     164                                                <th><?php esc_html_e( 'Provider', 'easyit-ai-chat' ); ?></th>
     165                                                <th><?php esc_html_e( 'Model', 'easyit-ai-chat' ); ?></th>
     166                                                <th><?php esc_html_e( 'Requests', 'easyit-ai-chat' ); ?></th>
     167                                                <th><?php esc_html_e( 'Input tokens', 'easyit-ai-chat' ); ?></th>
     168                                                <th><?php esc_html_e( 'Output tokens', 'easyit-ai-chat' ); ?></th>
     169                                                <th><?php esc_html_e( 'Est. cost', 'easyit-ai-chat' ); ?></th>
     170                                        </tr>
     171                                </thead>
     172                                <tbody>
     173                                <?php foreach ( $eaic_usage_by as $eaic_u_row ) : ?>
     174                                        <?php $eaic_priced = null !== EAIC_Usage::price_for( $eaic_u_row['provider'], $eaic_u_row['model'] ); ?>
     175                                        <tr>
     176                                                <td><?php echo esc_html( $eaic_u_row['provider'] ); ?></td>
     177                                                <td><?php echo esc_html( $eaic_u_row['model'] ? $eaic_u_row['model'] : '—' ); ?></td>
     178                                                <td>
     179                                                        <?php echo esc_html( number_format_i18n( (int) $eaic_u_row['requests'] ) ); ?>
     180                                                        <?php if ( (int) $eaic_u_row['est_requests'] > 0 ) : ?>
     181                                                                <span title="<?php esc_attr_e( 'Some requests did not report token counts, so tokens were estimated (~4 characters per token).', 'easyit-ai-chat' ); ?>">*</span>
     182                                                        <?php endif; ?>
     183                                                </td>
     184                                                <td><?php echo esc_html( number_format_i18n( (int) $eaic_u_row['input_tokens'] ) ); ?></td>
     185                                                <td><?php echo esc_html( number_format_i18n( (int) $eaic_u_row['output_tokens'] ) ); ?></td>
     186                                                <td>
     187                                                        <?php if ( $eaic_priced ) : ?>
     188                                                                $<?php echo esc_html( number_format_i18n( (float) $eaic_u_row['cost'], 4 ) ); ?>
     189                                                        <?php else : ?>
     190                                                                <em title="<?php esc_attr_e( 'No price known for this model. Add one under Settings → Security → Usage Budget.', 'easyit-ai-chat' ); ?>"><?php esc_html_e( 'unpriced', 'easyit-ai-chat' ); ?></em>
     191                                                        <?php endif; ?>
     192                                                </td>
     193                                        </tr>
     194                                <?php endforeach; ?>
     195                                </tbody>
     196                        </table>
     197                        <p class="description"><?php esc_html_e( '* includes requests where the provider did not report token counts (estimated). Costs are estimates from list prices; your provider invoice is the source of truth.', 'easyit-ai-chat' ); ?></p>
     198                <?php endif; ?>
    85199        </div>
    86200
    … …  
    200314        </div>
    201315
     316        <!-- Knowledge gaps -->
     317        <div class="eaic-card">
     318                <div class="eaic-card-title">
     319                        <span class="icon">🧩</span> <?php esc_html_e( 'Knowledge Gaps — What Your Chat Could Not Answer', 'easyit-ai-chat' ); ?>
     320                </div>
     321                <?php if ( empty( $eaic_gaps ) && empty( $eaic_downvoted ) ) : ?>
     322                        <p class="eaic-no-data"><?php esc_html_e( 'Nothing here yet. When Ask This Site or your Knowledge Base finds nothing for a visitor’s question, it is listed here so you know what content to add. Answers rated “not helpful” appear too.', 'easyit-ai-chat' ); ?></p>
     323                <?php endif; ?>
     324
     325                <?php if ( ! empty( $eaic_gaps ) ) : ?>
     326                        <table class="eaic-table">
     327                                <thead>
     328                                        <tr>
     329                                                <th><?php esc_html_e( 'Question with no match in your content', 'easyit-ai-chat' ); ?></th>
     330                                                <th class="eaic-col-num"><?php esc_html_e( 'Times asked', 'easyit-ai-chat' ); ?></th>
     331                                                <th><?php esc_html_e( 'Last asked', 'easyit-ai-chat' ); ?></th>
     332                                        </tr>
     333                                </thead>
     334                                <tbody>
     335                                <?php foreach ( $eaic_gaps as $eaic_gap ) : ?>
     336                                        <tr>
     337                                                <td><?php echo esc_html( $eaic_gap['question'] ); ?></td>
     338                                                <td class="eaic-col-num"><?php echo esc_html( number_format_i18n( (int) $eaic_gap['hits'] ) ); ?></td>
     339                                                <td><?php echo esc_html( date_i18n( 'M j, Y', strtotime( $eaic_gap['last_seen'] ) ) ); ?></td>
     340                                        </tr>
     341                                <?php endforeach; ?>
     342                                </tbody>
     343                        </table>
     344                        <p style="margin:12px 0 0">
     345                                <a class="button button-small" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=eaic_clear_gaps' ), 'eaic_clear_gaps' ) ); ?>" onclick="return confirm('<?php echo esc_js( __( 'Clear this list?', 'easyit-ai-chat' ) ); ?>');"><?php esc_html_e( 'Clear list', 'easyit-ai-chat' ); ?></a>
     346                        </p>
     347                <?php endif; ?>
     348
     349                <?php if ( ! empty( $eaic_downvoted ) ) : ?>
     350                        <h4 style="margin:18px 0 8px"><?php esc_html_e( 'Recent answers rated “not helpful”', 'easyit-ai-chat' ); ?></h4>
     351                        <table class="eaic-table">
     352                                <thead>
     353                                        <tr>
     354                                                <th><?php esc_html_e( 'Question', 'easyit-ai-chat' ); ?></th>
     355                                                <th><?php esc_html_e( 'Answer given', 'easyit-ai-chat' ); ?></th>
     356                                                <th><?php esc_html_e( 'Date', 'easyit-ai-chat' ); ?></th>
     357                                        </tr>
     358                                </thead>
     359                                <tbody>
     360                                <?php foreach ( $eaic_downvoted as $eaic_dv ) : ?>
     361                                        <tr>
     362                                                <td><?php echo esc_html( $eaic_dv['question'] ); ?></td>
     363                                                <td class="eaic-muted"><?php echo esc_html( $eaic_dv['answer'] ); ?></td>
     364                                                <td><?php echo esc_html( date_i18n( 'M j, Y', strtotime( $eaic_dv['date'] ) ) ); ?></td>
     365                                        </tr>
     366                                <?php endforeach; ?>
     367                                </tbody>
     368                        </table>
     369                <?php endif; ?>
     370        </div>
     371
    202372        <!-- Leads table -->
    203373        <div class="eaic-card">
    204                 <div class="eaic-card-title"><span class="icon">📧</span> <?php esc_html_e( 'Leads Collected', 'easyit-ai-chat' ); ?></div>
     374                <div class="eaic-card-title">
     375                        <span class="icon">📧</span> <?php esc_html_e( 'Leads Collected', 'easyit-ai-chat' ); ?>
     376                        <?php if ( ! empty( $eaic_leads ) ) : ?>
     377                                <a class="button button-small" style="margin-left:auto" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=eaic_export_leads' ), 'eaic_export_leads' ) ); ?>"><?php esc_html_e( 'Export CSV', 'easyit-ai-chat' ); ?></a>
     378                        <?php endif; ?>
     379                </div>
    205380                <?php if ( empty( $eaic_leads ) ) : ?>
    206381                        <p class="eaic-no-data"><?php esc_html_e( 'No leads yet. Leads appear when visitors submit the pre-chat form.', 'easyit-ai-chat' ); ?></p>
  • easyit-ai-chat/trunk/admin/views/knowledge-base-page.php

    r3617461 r3741982  
    1717$eaic_rag_enabled   = ! empty( $eaic_opts['rag_enabled'] );
    1818$eaic_embed_model   = isset( $eaic_opts['rag_embed_model'] ) ? $eaic_opts['rag_embed_model'] : 'nomic-embed-text';
     19$eaic_embed_provider_opt = isset( $eaic_opts['rag_embed_provider'] ) ? $eaic_opts['rag_embed_provider'] : 'auto';
     20$eaic_rag_probe          = new EAIC_RAG( $eaic_opts );
     21$eaic_embed_signature    = $eaic_rag_probe->embed_signature();
     22$eaic_indexed_signature  = (string) get_option( 'eaic_rag_embed_signature', '' );
     23$eaic_embed_stale        = '' !== $eaic_indexed_signature && $eaic_indexed_signature !== $eaic_embed_signature;
    1924$eaic_ollama_url    = ! empty( $eaic_opts['ollama_url'] ) ? $eaic_opts['ollama_url'] : 'http://localhost:11434';
    2025$eaic_chunk_size    = isset( $eaic_opts['rag_chunk_size'] ) ? (int) $eaic_opts['rag_chunk_size'] : 500;
    … …  
    5358                                </tr>
    5459                                <tr>
    55                                         <th><?php esc_html_e( 'Embedding Model', 'easyit-ai-chat' ); ?></th>
     60                                        <th><?php esc_html_e( 'Embedding Service', 'easyit-ai-chat' ); ?></th>
     61                                        <td>
     62                                                <select name="eaic_options[rag_embed_provider]">
     63                                                        <option value="auto" <?php selected( $eaic_embed_provider_opt, 'auto' ); ?>><?php esc_html_e( 'Automatic (follow the default chat provider)', 'easyit-ai-chat' ); ?></option>
     64                                                        <option value="openai" <?php selected( $eaic_embed_provider_opt, 'openai' ); ?>><?php esc_html_e( 'OpenAI (text-embedding-3-small)', 'easyit-ai-chat' ); ?></option>
     65                                                        <option value="gemini" <?php selected( $eaic_embed_provider_opt, 'gemini' ); ?>><?php esc_html_e( 'Google Gemini (gemini-embedding-001)', 'easyit-ai-chat' ); ?></option>
     66                                                        <option value="ollama" <?php selected( $eaic_embed_provider_opt, 'ollama' ); ?>><?php esc_html_e( 'Ollama (self-hosted, free)', 'easyit-ai-chat' ); ?></option>
     67                                                </select>
     68                                                <p class="description">
     69                                                        <?php
     70                                                        printf(
     71                                                                /* translators: %s: embedding service in use, e.g. "openai:text-embedding-3-small" */
     72                                                                esc_html__( 'Currently using: %s. OpenAI and Gemini need no extra server, but your site text is sent to that provider to be embedded. Costs are tiny (a few cents for a whole site).', 'easyit-ai-chat' ),
     73                                                                '<code>' . esc_html( $eaic_embed_signature ) . '</code>'
     74                                                        );
     75                                                        ?>
     76                                                </p>
     77                                                <?php if ( $eaic_embed_stale ) : ?>
     78                                                <p class="description" style="color:#b32d2e;font-weight:600">
     79                                                        <?php esc_html_e( 'Your indexed content was created with a different embedding model. Re-index it (the button below) and re-process uploaded documents so search stays accurate. Until then, keyword search is used.', 'easyit-ai-chat' ); ?>
     80                                                </p>
     81                                                <?php endif; ?>
     82                                        </td>
     83                                </tr>
     84                                <tr>
     85                                        <th><?php esc_html_e( 'Ollama Embedding Model', 'easyit-ai-chat' ); ?></th>
    5686                                        <td>
    5787                                                <input type="text" name="eaic_options[rag_embed_model]" value="<?php echo esc_attr( $eaic_embed_model ); ?>" class="regular-text" placeholder="nomic-embed-text">
    … …  
    86116                                                <input type="number" name="eaic_options[rag_top_k]" value="<?php echo esc_attr( $eaic_top_k ); ?>" min="1" max="10" class="small-text">
    87117                                                <p class="description"><?php esc_html_e( 'How many chunks to inject per query.', 'easyit-ai-chat' ); ?></p>
     118                                        </td>
     119                                </tr>
     120                                <tr>
     121                                        <th><?php esc_html_e( 'Show Sources', 'easyit-ai-chat' ); ?></th>
     122                                        <td>
     123                                                <label>
     124                                                        <input type="hidden" name="eaic_options[citations_enabled]" value="0">
     125                                                        <input type="checkbox" name="eaic_options[citations_enabled]" value="1" <?php checked( ! empty( $eaic_opts['citations_enabled'] ) ); ?>>
     126                                                        <?php esc_html_e( 'Show "Sources" links under answers drawn from your site content or documents', 'easyit-ai-chat' ); ?>
     127                                                </label>
     128                                                <p class="description"><?php esc_html_e( 'Published pages link to their URL; uploaded documents are listed by title only.', 'easyit-ai-chat' ); ?></p>
    88129                                        </td>
    89130                                </tr>
  • easyit-ai-chat/trunk/admin/views/settings-page.php

    r3617603 r3741982  
    571571
    572572                                <div class="eaic-card">
     573                                        <div class="eaic-card-title"><span class="icon">📧</span> <?php esc_html_e( 'Lead Capture & Weekly Summary', 'easyit-ai-chat' ); ?></div>
     574
     575                                        <label class="eaic-check-row">
     576                                                <input type="checkbox" name="<?php echo esc_attr( $eaic_option_key ); ?>[lead_main_enabled]" value="1" <?php checked( $eaic_opts['lead_main_enabled'] ); ?>>
     577                                                <div>
     578                                                        <div class="eaic-check-label"><?php esc_html_e( 'Ask visitors for their name & email in the main chat', 'easyit-ai-chat' ); ?></div>
     579                                                        <div class="eaic-check-desc"><?php esc_html_e( 'Shows a short, skippable card at the start of a new chat. Leads appear on the Analytics page and can be exported as CSV. Uses the title and subtitle from the WooCommerce lead form settings.', 'easyit-ai-chat' ); ?></div>
     580                                                </div>
     581                                        </label>
     582
     583                                        <label class="eaic-check-row">
     584                                                <input type="checkbox" name="<?php echo esc_attr( $eaic_option_key ); ?>[lead_notify_enabled]" value="1" <?php checked( $eaic_opts['lead_notify_enabled'] ); ?>>
     585                                                <div>
     586                                                        <div class="eaic-check-label"><?php esc_html_e( 'Email me when a new lead arrives', 'easyit-ai-chat' ); ?></div>
     587                                                        <div class="eaic-check-desc"><?php esc_html_e( 'Applies to every chat widget and WooCommerce bot. At most 20 emails per hour.', 'easyit-ai-chat' ); ?></div>
     588                                                </div>
     589                                        </label>
     590
     591                                        <div class="eaic-field" style="margin-top:12px">
     592                                                <label class="eaic-label" for="eaic-lead-notify-email"><?php esc_html_e( 'Send lead notifications to', 'easyit-ai-chat' ); ?></label>
     593                                                <input id="eaic-lead-notify-email" type="email" class="regular-text" name="<?php echo esc_attr( $eaic_option_key ); ?>[lead_notify_email]" value="<?php echo esc_attr( $eaic_opts['lead_notify_email'] ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
     594                                        </div>
     595
     596                                        <label class="eaic-check-row">
     597                                                <input type="checkbox" name="<?php echo esc_attr( $eaic_option_key ); ?>[digest_enabled]" value="1" <?php checked( $eaic_opts['digest_enabled'] ); ?>>
     598                                                <div>
     599                                                        <div class="eaic-check-label"><?php esc_html_e( 'Send me a weekly summary email', 'easyit-ai-chat' ); ?></div>
     600                                                        <div class="eaic-check-desc"><?php esc_html_e( 'Conversations, questions answered, AI cost, new leads, and the questions your chat could not answer. Nothing is sent in a week with no activity.', 'easyit-ai-chat' ); ?></div>
     601                                                </div>
     602                                        </label>
     603
     604                                        <div class="eaic-field" style="margin-top:12px">
     605                                                <label class="eaic-label" for="eaic-digest-email"><?php esc_html_e( 'Send the summary to', 'easyit-ai-chat' ); ?></label>
     606                                                <input id="eaic-digest-email" type="email" class="regular-text" name="<?php echo esc_attr( $eaic_option_key ); ?>[digest_email]" value="<?php echo esc_attr( $eaic_opts['digest_email'] ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
     607                                        </div>
     608                                </div>
     609
     610                                <div class="eaic-card">
    573611                                        <div class="eaic-card-title"><span class="icon">🤖</span> <?php esc_html_e( 'AI Avatar', 'easyit-ai-chat' ); ?></div>
    574612                                        <div class="eaic-field">
    … …  
    630668                                                        <div class="eaic-field-desc"><?php esc_html_e( 'Hard cap across all sessions from one IP address.', 'easyit-ai-chat' ); ?></div>
    631669                                                </div>
     670                                        </div>
     671                                </div>
     672
     673                                <div class="eaic-card">
     674                                        <div class="eaic-card-title"><span class="icon">💰</span> <?php esc_html_e( 'Usage Budget', 'easyit-ai-chat' ); ?></div>
     675                                        <p class="eaic-field-desc" style="margin-top:0"><?php esc_html_e( 'Pause the chat automatically when your AI usage reaches a limit, so a traffic spike or abuse can never run up your API bill. Set a limit to 0 to disable it. Usage is tracked on the Analytics page.', 'easyit-ai-chat' ); ?></p>
     676
     677                                        <div class="eaic-field-grid">
     678                                                <div class="eaic-field">
     679                                                        <label class="eaic-label" for="eaic-budget-daily"><?php esc_html_e( 'Daily token limit', 'easyit-ai-chat' ); ?></label>
     680                                                        <input id="eaic-budget-daily" type="number" min="0" step="1000" name="<?php echo esc_attr( $eaic_option_key ); ?>[budget_daily_tokens]" value="<?php echo (int) $eaic_opts['budget_daily_tokens']; ?>">
     681                                                        <div class="eaic-field-desc"><?php esc_html_e( 'Input + output tokens per day. 0 = unlimited.', 'easyit-ai-chat' ); ?></div>
     682                                                </div>
     683                                                <div class="eaic-field">
     684                                                        <label class="eaic-label" for="eaic-budget-monthly"><?php esc_html_e( 'Monthly token limit', 'easyit-ai-chat' ); ?></label>
     685                                                        <input id="eaic-budget-monthly" type="number" min="0" step="1000" name="<?php echo esc_attr( $eaic_option_key ); ?>[budget_monthly_tokens]" value="<?php echo (int) $eaic_opts['budget_monthly_tokens']; ?>">
     686                                                        <div class="eaic-field-desc"><?php esc_html_e( 'Input + output tokens per calendar month. 0 = unlimited.', 'easyit-ai-chat' ); ?></div>
     687                                                </div>
     688                                                <div class="eaic-field">
     689                                                        <label class="eaic-label" for="eaic-budget-usd"><?php esc_html_e( 'Monthly cost limit (USD)', 'easyit-ai-chat' ); ?></label>
     690                                                        <input id="eaic-budget-usd" type="number" min="0" step="0.01" name="<?php echo esc_attr( $eaic_option_key ); ?>[budget_monthly_usd]" value="<?php echo esc_attr( $eaic_opts['budget_monthly_usd'] ); ?>">
     691                                                        <div class="eaic-field-desc"><?php esc_html_e( 'Estimated from list prices, so treat it as a guide, not your exact invoice. 0 = unlimited.', 'easyit-ai-chat' ); ?></div>
     692                                                </div>
     693                                        </div>
     694
     695                                        <div class="eaic-field">
     696                                                <label class="eaic-label" for="eaic-budget-message"><?php esc_html_e( 'Message shown to visitors when paused', 'easyit-ai-chat' ); ?></label>
     697                                                <input id="eaic-budget-message" type="text" class="regular-text" name="<?php echo esc_attr( $eaic_option_key ); ?>[budget_message]" value="<?php echo esc_attr( $eaic_opts['budget_message'] ); ?>" placeholder="<?php esc_attr_e( 'The assistant is temporarily unavailable. Please try again later.', 'easyit-ai-chat' ); ?>">
     698                                        </div>
     699
     700                                        <label class="eaic-check-row">
     701                                                <input type="hidden" name="<?php echo esc_attr( $eaic_option_key ); ?>[budget_alert_enabled]" value="0">
     702                                                <input type="checkbox" name="<?php echo esc_attr( $eaic_option_key ); ?>[budget_alert_enabled]" value="1" <?php checked( $eaic_opts['budget_alert_enabled'] ); ?>>
     703                                                <div>
     704                                                        <div class="eaic-check-label"><?php esc_html_e( 'Email me when a limit is reached', 'easyit-ai-chat' ); ?></div>
     705                                                        <div class="eaic-check-desc"><?php esc_html_e( 'Sent once per period to the Abuse Alert email (or the site admin email if none is set).', 'easyit-ai-chat' ); ?></div>
     706                                                </div>
     707                                        </label>
     708
     709                                        <div class="eaic-field" style="margin-top:12px">
     710                                                <label class="eaic-label" for="eaic-price-overrides"><?php esc_html_e( 'Custom model prices (optional)', 'easyit-ai-chat' ); ?></label>
     711                                                <textarea id="eaic-price-overrides" rows="3" class="large-text code" name="<?php echo esc_attr( $eaic_option_key ); ?>[usage_price_overrides]" placeholder="llama-3.3-70b=0.88,0.88"><?php echo esc_textarea( $eaic_opts['usage_price_overrides'] ); ?></textarea>
     712                                                <div class="eaic-field-desc"><?php esc_html_e( 'One per line: model-name-fragment=input price,output price in USD per 1 million tokens. Needed for cost estimates on Together AI and custom providers; common OpenAI, Claude, Gemini and DeepSeek models are built in.', 'easyit-ai-chat' ); ?></div>
    632713                                        </div>
    633714                                </div>
  • easyit-ai-chat/trunk/easyit-ai-chat.php

    r3617603 r3741982  
    44 * Plugin URI:        https://github.com/easybdit/easyit-ai-chat
    55 * Description:       Unified AI chatbot for WordPress. Connect Ollama, OpenAI, Anthropic (Claude), DeepSeek, Google Gemini and Together AI with one shortcode [eaic_chat]. Free, open-source, no tracking.
    6  * Version:           2.7.0
     6 * Version:           2.8.0
    77 * Requires at least: 6.0
    88 * Requires PHP:      8.0
    … …  
    2020}
    2121
    22 define( 'EAIC_VERSION',  '2.7.0' );
     22define( 'EAIC_VERSION',  '2.8.0' );
    2323define( 'EAIC_FILE',     __FILE__ );
    2424define( 'EAIC_DIR',      plugin_dir_path( __FILE__ ) );
    2525define( 'EAIC_URL',      plugin_dir_url( __FILE__ ) );
    2626define( 'EAIC_BASENAME', plugin_basename( __FILE__ ) );
    27 
    28 // Freemius SDK — must load before plugin init.
    29 if ( ! function_exists( 'eaic_fs' ) ) {
    30         function eaic_fs() {
    31                 global $eaic_fs;
    32                 if ( ! isset( $eaic_fs ) ) {
    33                         require_once EAIC_DIR . 'vendor/freemius/start.php';
    34                         $eaic_fs = fs_dynamic_init( array(
    35                                 'id'                  => '30864',
    36                                 'slug'                => 'easyit-ai-chat',
    37                                 'type'                => 'plugin',
    38                                 'public_key'          => 'pk_ee7766daaf807e36db27264276b58',
    39                                 'is_premium'          => false,
    40                                 'premium_suffix'      => 'Pro',
    41                                 // v2.4.0 — every formerly-Pro feature now ships free; nothing left to upsell.
    42                                 'has_premium_version' => false,
    43                                 'has_addons'          => false,
    44                                 'has_paid_plans'      => false,
    45                                 'is_org_compliant'    => true,
    46                                 'menu'                => array(
    47                                         'support' => false,
    48                                 ),
    49                         ) );
    50                 }
    51                 return $eaic_fs;
    52         }
    53         eaic_fs();
    54         do_action( 'eaic_fs_loaded' );
    55 }
    5627
    5728require_once EAIC_DIR . 'includes/class-eaic-options.php';
    … …  
    6435require_once EAIC_DIR . 'includes/providers/class-eaic-together.php';
    6536require_once EAIC_DIR . 'includes/providers/class-eaic-custom.php';
     37require_once EAIC_DIR . 'includes/class-eaic-usage.php';
     38require_once EAIC_DIR . 'includes/class-eaic-insights.php';
    6639require_once EAIC_DIR . 'includes/class-eaic-db.php';
    6740require_once EAIC_DIR . 'includes/class-eaic-rag-db.php';
    … …  
    11992                update_option( 'eaic_db_version', EAIC_VERSION );
    12093        }
     94        // Schema changes shipped between version bumps (usage table, message sources column).
     95        if ( (int) get_option( 'eaic_schema_rev', 0 ) < 2 ) {
     96                EAIC_DB::create_tables();
     97                update_option( 'eaic_schema_rev', 2 );
     98        }
     99        EAIC_Insights::remember_first_seen();
     100        EAIC_Insights::boot();
    121101        EAIC_Lead_Ajax::init();
    122102        new EAIC_Engine();
    … …  
    174154                wp_unschedule_event( $timestamp, 'eaic_daily_purge' );
    175155        }
     156        $digest = wp_next_scheduled( 'eaic_weekly_digest' );
     157        if ( $digest ) {
     158                wp_unschedule_event( $digest, 'eaic_weekly_digest' );
     159        }
    176160}
    177161register_deactivation_hook( __FILE__, 'eaic_deactivate' );
  • easyit-ai-chat/trunk/includes/class-eaic-db.php

    r3617603 r3741982  
    6565                        role       VARCHAR(20)     NOT NULL DEFAULT 'user',
    6666                        content    LONGTEXT        NOT NULL,
     67                        sources    TEXT            NULL,
    6768                        created_at DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    6869                        PRIMARY KEY  (id),
    … …  
    135136                dbDelta( $chunks );
    136137                dbDelta( $attachments );
     138                EAIC_Usage::create_table();
     139                EAIC_Insights::create_table();
    137140        }
    138141
    … …  
    374377                        $wpdb->prepare(
    375378                                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    376                                 "SELECT id, role, content, created_at FROM {$table} WHERE session_id = %d ORDER BY id ASC",
     379                                "SELECT id, role, content, sources, created_at FROM {$table} WHERE session_id = %d ORDER BY id ASC",
    377380                                (int) $session['id']
    378381                        ),
    … …  
    386389                foreach ( $rows as &$row ) {
    387390                        $row['attachments'] = isset( $attachments[ $row['id'] ] ) ? $attachments[ $row['id'] ] : array();
     391                        $decoded_sources    = ! empty( $row['sources'] ) ? json_decode( $row['sources'], true ) : array();
     392                        $row['sources']     = is_array( $decoded_sources ) ? $decoded_sources : array();
    388393                }
    389394                unset( $row );
    … …  
    404409         * @param string $role    'user' or 'assistant'.
    405410         * @param string $content Message content.
     411         * @param array  $sources Optional citation sources: [ ['title' => string, 'url' => string], ... ].
    406412         * @return int The new message row ID (0 on failure).
    407413         */
    408         public static function add_message( $uuid, $role, $content ) {
     414        public static function add_message( $uuid, $role, $content, array $sources = array() ) {
    409415                global $wpdb;
    410416
    … …  
    424430                                'role'       => $role,
    425431                                'content'    => (string) $content,
     432                                'sources'    => ! empty( $sources ) ? wp_json_encode( array_values( $sources ) ) : null,
    426433                        ),
    427                         array( '%d', '%s', '%s' )
     434                        array( '%d', '%s', '%s', '%s' )
    428435                );
    429436
  • easyit-ai-chat/trunk/includes/class-eaic-engine.php

    r3617603 r3741982  
    249249                        $this->maybe_send_abuse_alert( $opts );
    250250                        wp_send_json_error( array( 'message' => __( 'Too many requests. Please wait a moment.', 'easyit-ai-chat' ) ), 429 );
     251                }
     252
     253                // Budget caps (daily / monthly tokens, monthly cost) — pause the bot instead of running up the API bill.
     254                $over_cap = EAIC_Usage::exceeded_cap( $opts );
     255                if ( '' !== $over_cap ) {
     256                        EAIC_Usage::maybe_notify( $over_cap, $opts );
     257                        $budget_msg = trim( (string) ( $opts['budget_message'] ?? '' ) );
     258                        wp_send_json_error(
     259                                array( 'message' => '' !== $budget_msg ? $budget_msg : __( 'The assistant is temporarily unavailable. Please try again later.', 'easyit-ai-chat' ) ),
     260                                429
     261                        );
    251262                }
    252263
    … …  
    476487                        = $this->resolve_request( $user_id, $guest_token );
    477488
     489                list( $system_prompt, $sources ) = $this->apply_rag( $opts, $message, $system_prompt );
     490
    478491                try {
    479                         $ai_reply = $this->get_provider( $provider )->chat( $messages, $system_prompt );
     492                        $ai_provider = $this->get_provider( $provider );
     493                        $ai_reply    = $ai_provider->chat( $messages, $system_prompt );
    480494                } catch ( Exception $e ) {
    481495                        wp_send_json_error( array( 'message' => $this->public_error_message( $e ) ) );
     496                }
     497                $this->record_usage( $provider, $opts, $ai_provider, $messages, $system_prompt, $ai_reply );
     498                if ( '' === trim( $ai_reply ) ) {
     499                        $sources = array();
    482500                }
    483501
    … …  
    485503                if ( ! EAIC_Options::get( 'disable_storage', false ) ) {
    486504                        $user_msg_id = EAIC_DB::add_message( $uuid, 'user', $stored_message );
    487                         EAIC_DB::add_message( $uuid, 'assistant', $ai_reply );
     505                        EAIC_DB::add_message( $uuid, 'assistant', $ai_reply, $sources );
    488506                        if ( ! empty( $attachment_ids ) ) {
    489507                                EAIC_DB::link_attachments_to_message( $user_msg_id, $attachment_ids, $uuid );
    … …  
    496514
    497515                wp_send_json_success( array(
     516                        'sources'  => $sources,
    498517                        'reply'    => $ai_reply,
    499518                        'session'  => $uuid,
    … …  
    579598
    580599                // ---- RAG context injection ----
    581                 $rag = new EAIC_RAG( $opts );
    582                 if ( $rag->is_enabled() ) {
    583                         $rag_context = $rag->build_context( $message );
    584                         if ( '' !== $rag_context ) {
    585                                 $system_prompt = $rag_context . ( '' !== $system_prompt ? "\n\n" . $system_prompt : '' );
    586                         }
    587                 }
     600                list( $system_prompt, $sources ) = $this->apply_rag( $opts, $message, $system_prompt );
    588601                // ---- End RAG context injection ----
    589602
    590603                $ai_reply = '';
    591604                try {
    592                         $ai_reply = $this->get_provider( $provider )->stream_chat( $messages, $system_prompt );
     605                        $ai_provider = $this->get_provider( $provider );
     606                        try {
     607                                $ai_reply = $ai_provider->stream_chat( $messages, $system_prompt );
     608                        } catch ( Exception $stream_error ) {
     609                                // Streaming can fail on hosts/proxies that block it. If nothing has reached the
     610                                // visitor yet, retry once the ordinary way so the chat still answers.
     611                                if ( EAIC_Provider::chunks_sent() > 0 ) {
     612                                        throw $stream_error;
     613                                }
     614                                $ai_reply = $ai_provider->chat( $messages, $system_prompt );
     615                                if ( '' !== $ai_reply ) {
     616                                        EAIC_Provider::sse_send( 'chunk', array( 'text' => $ai_reply ) );
     617                                }
     618                        }
    593619                } catch ( Exception $e ) {
    594620                        EAIC_Provider::sse_send( 'error', array( 'message' => $this->public_error_message( $e ) ) );
    … …  
    597623                }
    598624
     625                $this->record_usage( $provider, $opts, $ai_provider, $messages, $system_prompt, $ai_reply );
     626
     627                // Tell the widget which pages/documents the answer was drawn from.
     628                if ( ! empty( $sources ) && '' !== trim( $ai_reply ) ) {
     629                        EAIC_Provider::sse_send( 'sources', array( 'sources' => $sources ) );
     630                } else {
     631                        $sources = array();
     632                }
     633
    599634                // Persist to DB (skip entirely in no-storage mode).
    600635                $new_title = null;
    601636                if ( ! $opts['disable_storage'] ) {
    602637                        $user_msg_id = EAIC_DB::add_message( $uuid, 'user', $stored_message );
    603                         EAIC_DB::add_message( $uuid, 'assistant', $ai_reply );
     638                        EAIC_DB::add_message( $uuid, 'assistant', $ai_reply, $sources );
    604639                        if ( ! empty( $attachment_ids ) ) {
    605640                                EAIC_DB::link_attachments_to_message( $user_msg_id, $attachment_ids, $uuid );
    … …  
    623658
    624659                exit;
     660        }
     661
     662        /**
     663         * Prepend knowledge-base context ("Ask This Site" / uploaded documents) to the system prompt.
     664         *
     665         * @param array  $opts          Plugin options.
     666         * @param string $message       The visitor's message.
     667         * @param string $system_prompt Current system prompt.
     668         * @return array{0:string,1:array} Updated system prompt and the citation sources behind it.
     669         */
     670        private function apply_rag( array $opts, $message, $system_prompt ) {
     671                $rag = new EAIC_RAG( $opts );
     672                if ( ! $rag->is_enabled() ) {
     673                        return array( $system_prompt, array() );
     674                }
     675                $rag_context = $rag->build_context( $message );
     676                if ( '' === $rag_context ) {
     677                        // Nothing in the knowledge base matched: remember the question so the owner can fill the gap.
     678                        if ( empty( $opts['disable_storage'] ) ) {
     679                                EAIC_Insights::log_miss( $message );
     680                        }
     681                        return array( $system_prompt, array() );
     682                }
     683                return array(
     684                        $rag_context . ( '' !== $system_prompt ? "\n\n" . $system_prompt : '' ),
     685                        $rag->get_last_sources(),
     686                );
     687        }
     688
     689        /**
     690         * Log token usage for a finished request. Never lets a tracking failure break the chat.
     691         *
     692         * @param string        $provider      Provider slug.
     693         * @param array         $opts          Plugin options.
     694         * @param EAIC_Provider $ai_provider   Provider instance that handled the request.
     695         * @param array         $messages      Messages sent.
     696         * @param string        $system_prompt System prompt sent.
     697         * @param string        $reply         Reply received.
     698         * @return void
     699         */
     700        private function record_usage( $provider, array $opts, $ai_provider, array $messages, $system_prompt, $reply ) {
     701                try {
     702                        $model = isset( $opts[ $provider . '_model' ] ) ? (string) $opts[ $provider . '_model' ] : '';
     703                        EAIC_Usage::record( $provider, $model, $ai_provider->get_usage(), $messages, (string) $system_prompt, (string) $reply );
     704                } catch ( \Throwable $e ) {
     705                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     706                        error_log( '[EAIC Usage] Failed to record usage: ' . $e->getMessage() );
     707                }
    625708        }
    626709
  • easyit-ai-chat/trunk/includes/class-eaic-lead-ajax.php

    r3617353 r3741982  
    7171
    7272                EAIC_Lead_DB::save( $session_id, $user_id, $name, $email, $context, $product_id );
     73                EAIC_Insights::notify_new_lead( $name, $email, $context );
    7374
    7475                wp_send_json_success( array( 'saved' => true ) );
  • easyit-ai-chat/trunk/includes/class-eaic-options.php

    r3617603 r3741982  
    116116                        // v2.3.0 — RAG
    117117                        'rag_enabled'                  => false,
    118                         'rag_embed_model'              => 'nomic-embed-text',
     118                        'rag_embed_provider'           => 'auto', // auto | ollama | openai | gemini
     119                        'rag_embed_model'              => 'nomic-embed-text', // Ollama embedding model
    119120                        'rag_chunk_size'               => 500,
    120121                        'rag_chunk_overlap'            => 50,
    … …  
    128129                        'attachments_upload_max_image_mb' => 5,
    129130                        'attachments_upload_max_doc_mb'   => 10,
     131                        // v2.8.0 — Source citations, usage tracking & budget caps
     132                        'citations_enabled'               => true,
     133                        'budget_daily_tokens'             => 0,     // 0 = no limit
     134                        'budget_monthly_tokens'           => 0,     // 0 = no limit
     135                        'budget_monthly_usd'              => 0,     // 0 = no limit (estimated cost)
     136                        'budget_message'                  => '',
     137                        'budget_alert_enabled'            => true,
     138                        'digest_enabled'                  => false, // weekly summary e-mail (opt-in)
     139                        'digest_email'                    => '',
     140                        'lead_main_enabled'               => false, // pre-chat name/e-mail card in the main chat (opt-in)
     141                        'lead_notify_enabled'             => true,
     142                        'lead_notify_email'               => '',
     143                        'usage_price_overrides'           => '',    // one "model-substring=input,output" (USD per 1M tokens) per line
    130144                );
    131145        }
  • easyit-ai-chat/trunk/includes/class-eaic-provider.php

    r3617353 r3741982  
    1919        protected $opts;
    2020
     21        /** @var int Number of text chunks already sent to the browser in this request. */
     22        private static $chunks_sent = 0;
     23
     24        /**
     25         * How many text chunks this request has already streamed to the visitor.
     26         *
     27         * @return int
     28         */
     29        public static function chunks_sent() {
     30                return self::$chunks_sent;
     31        }
     32
     33        /** @var array{input:int,output:int}|null Token usage reported by the last request. */
     34        protected $usage = null;
     35
    2136        public function __construct( array $opts ) {
    2237                $this->opts = $opts;
     38        }
     39
     40        /**
     41         * Token usage reported by the provider for the last request, or null when it didn't report any.
     42         *
     43         * @return array{input:int,output:int}|null
     44         */
     45        public function get_usage() {
     46                return $this->usage;
     47        }
     48
     49        /**
     50         * Remember token counts from a provider response.
     51         *
     52         * @param mixed $input  Prompt/input tokens.
     53         * @param mixed $output Completion/output tokens.
     54         * @return void
     55         */
     56        protected function set_usage( $input, $output ) {
     57                $input  = max( 0, (int) $input );
     58                $output = max( 0, (int) $output );
     59                if ( $input + $output > 0 ) {
     60                        $this->usage = array( 'input' => $input, 'output' => $output );
     61                }
    2362        }
    2463
    … …  
    4887
    4988        /**
     89         * Whether real token streaming can be used (needs cURL). Without it providers fall
     90         * back to the buffered chat() path so the chat still works, just without live typing.
     91         *
     92         * @return bool
     93         */
     94        protected function can_stream() {
     95                return function_exists( 'curl_init' );
     96        }
     97
     98        /**
     99         * System prompt + role/content messages in OpenAI chat format.
     100         *
     101         * @param array  $messages Conversation history.
     102         * @param string $system   System prompt.
     103         * @return array
     104         */
     105        protected function plain_messages( array $messages, $system ) {
     106                $out = array();
     107                if ( '' !== $system ) {
     108                        $out[] = array( 'role' => 'system', 'content' => $system );
     109                }
     110                foreach ( $messages as $m ) {
     111                        $out[] = array( 'role' => $m['role'], 'content' => $m['content'] );
     112                }
     113                return $out;
     114        }
     115
     116        /**
     117         * Stream an OpenAI-style `/chat/completions` endpoint (OpenAI, DeepSeek, most compatible
     118         * gateways), emitting an SSE `chunk` event per token.
     119         *
     120         * @param string $url           Endpoint URL.
     121         * @param array  $body          Request body (without stream flags).
     122         * @param array  $headers       Extra headers (Authorization).
     123         * @param int    $timeout       Timeout in seconds.
     124         * @param bool   $include_usage Ask the API to report token usage in the final chunk.
     125         * @return string Full assembled reply.
     126         * @throws RuntimeException On transport / HTTP errors.
     127         */
     128        protected function stream_openai_format( $url, array $body, array $headers, $timeout, $include_usage = true ) {
     129                $body['stream'] = true;
     130                if ( $include_usage ) {
     131                        $body['stream_options'] = array( 'include_usage' => true );
     132                }
     133
     134                $full_reply = '';
     135                $this->http_stream(
     136                        $url,
     137                        $body,
     138                        $headers,
     139                        $timeout,
     140                        function ( $line ) use ( &$full_reply ) {
     141                                if ( 0 !== strpos( $line, 'data:' ) ) {
     142                                        return;
     143                                }
     144                                $json = trim( substr( $line, 5 ) );
     145                                if ( '' === $json || '[DONE]' === $json ) {
     146                                        return;
     147                                }
     148                                $chunk = json_decode( $json, true );
     149                                if ( ! is_array( $chunk ) ) {
     150                                        return;
     151                                }
     152                                if ( ! empty( $chunk['usage'] ) ) {
     153                                        $this->set_usage( $chunk['usage']['prompt_tokens'] ?? 0, $chunk['usage']['completion_tokens'] ?? 0 );
     154                                }
     155                                $text = $chunk['choices'][0]['delta']['content'] ?? '';
     156                                if ( is_string( $text ) && '' !== $text ) {
     157                                        $full_reply .= $text;
     158                                        self::sse_send( 'chunk', array( 'text' => $text ) );
     159                                }
     160                        }
     161                );
     162
     163                return $full_reply;
     164        }
     165
     166        /**
    50167         * Health-check: returns true if provider responds.
    51168         *
    … …  
    61178         */
    62179        public static function sse_send( $event, array $data ) {
     180                if ( 'chunk' === $event ) {
     181                        ++self::$chunks_sent;
     182                }
    63183                // 2 KB padding pushes past Apache/Nginx send-buffer thresholds so each
    64184                // event is delivered immediately instead of waiting for the buffer to fill.
  • easyit-ai-chat/trunk/includes/class-eaic-rag.php

    r3617461 r3741982  
    2222        private $opts;
    2323
     24        /**
     25         * Sources behind the context returned by the last build_context() call.
     26         *
     27         * @var array<int,array{title:string,url:string}>
     28         */
     29        private $last_sources = array();
     30
    2431        public function __construct( array $opts ) {
    2532                $this->opts = $opts;
     33        }
     34
     35        /**
     36         * Citation sources (documents / posts) that fed the last build_context() call.
     37         *
     38         * @return array<int,array{title:string,url:string}>
     39         */
     40        public function get_last_sources() {
     41                return $this->last_sources;
    2642        }
    2743
    … …  
    5167         */
    5268        public function build_context( $query ) {
     69                $this->last_sources = array();
     70
    5371                if ( ! $this->is_enabled() ) {
    5472                        return '';
    … …  
    7795
    7896                if ( $use_semantic ) {
    79                         // Cosine similarity search.
     97                        // Cosine similarity search. Vectors from a different embedding model have a
     98                        // different length and can't be compared, so skip them instead of scoring nonsense.
     99                        $dims = count( $query_embedding );
    80100                        foreach ( $all_chunks as $chunk ) {
    81101                                $embedding = json_decode( $chunk['embedding'], true );
    82                                 if ( ! is_array( $embedding ) || empty( $embedding ) ) {
     102                                if ( ! is_array( $embedding ) || count( $embedding ) !== $dims ) {
    83103                                        continue;
    84104                                }
    85105                                $score    = $this->cosine_similarity( $query_embedding, $embedding );
    86                                 $scored[] = array( 'content' => $chunk['content'], 'score' => $score );
    87                         }
    88                 } else {
     106                                $scored[] = array( 'content' => $chunk['content'], 'score' => $score, 'document_id' => (int) $chunk['document_id'] );
     107                        }
     108                        // Nothing comparable (e.g. the index was built with another embedding model): use keywords.
     109                        if ( empty( $scored ) ) {
     110                                $use_semantic = false;
     111                        }
     112                }
     113
     114                if ( ! $use_semantic ) {
    89115                        // Keyword fallback: score by how many query words appear in the chunk.
    90116                        $words = array_filter( explode( ' ', mb_strtolower( $query ) ), function ( $w ) {
    … …  
    104130                                }
    105131                                if ( $hits > 0 ) {
    106                                         $scored[] = array( 'content' => $chunk['content'], 'score' => $hits / $word_count );
     132                                        $scored[] = array( 'content' => $chunk['content'], 'score' => $hits / $word_count, 'document_id' => (int) $chunk['document_id'] );
    107133                                }
    108134                        }
    … …  
    118144                } );
    119145
     146                // Context only needs to be "possibly relevant", but a citation is a claim of
     147                // "this is where the answer came from": cite only chunks close to the best match
     148                // (and, in noisy keyword mode, matching at least a third of the query words).
     149                $cite_min      = max( $use_semantic ? $threshold : 0.34, 0.75 * (float) $scored[0]['score'] );
    120150                $context_parts = array();
     151                $source_doc_ids = array();
    121152                $count         = 0;
    122153                foreach ( $scored as $item ) {
    … …  
    126157                        if ( (float) $item['score'] >= $threshold ) {
    127158                                $context_parts[] = trim( $item['content'] );
     159                                if ( (float) $item['score'] >= $cite_min ) {
     160                                        $source_doc_ids[] = (int) $item['document_id'];
     161                                }
    128162                                $count++;
    129163                        }
    … …  
    142176                // lists the actual matching items — not whatever the embedding model returned.
    143177                if ( ! empty( $count_chunks ) ) {
    144                         $context_parts = $count_chunks;
    145                 }
     178                        $context_parts  = $count_chunks;
     179                        $source_doc_ids = array();
     180                        foreach ( $all_chunks as $chunk ) {
     181                                if ( in_array( trim( $chunk['content'] ), $count_chunks, true ) ) {
     182                                        $source_doc_ids[] = (int) $chunk['document_id'];
     183                                }
     184                        }
     185                }
     186
     187                $this->last_sources = $this->resolve_sources( $source_doc_ids );
    146188
    147189                $context = implode( "\n\n---\n\n", $context_parts );
    … …  
    160202                                ? "The VERIFIED COUNT above is the authoritative answer — state it directly. List the actual items from the supporting data with their name, room/location, tag number, and status."
    161203                                : "Answer using only the data above. Use exact item names and numbers. Format with bullet points or a table." );
     204        }
     205
     206        /**
     207         * Turn matched document IDs into display-ready citations (max 3, de-duplicated, best match first).
     208         * Auto-indexed posts link to their permalink; uploaded files are shown by title only.
     209         *
     210         * @param int[] $doc_ids Document IDs in relevance order (may repeat).
     211         * @return array<int,array{title:string,url:string}>
     212         */
     213        private function resolve_sources( array $doc_ids ) {
     214                if ( isset( $this->opts['citations_enabled'] ) && empty( $this->opts['citations_enabled'] ) ) {
     215                        return array();
     216                }
     217
     218                $sources = array();
     219                foreach ( array_unique( $doc_ids ) as $doc_id ) {
     220                        if ( count( $sources ) >= 3 ) {
     221                                break;
     222                        }
     223                        $doc = EAIC_RAG_DB::get_document( $doc_id );
     224                        if ( ! $doc ) {
     225                                continue;
     226                        }
     227                        if ( 'post' === $doc['source_type'] && (int) $doc['source_id'] > 0 ) {
     228                                $post = get_post( (int) $doc['source_id'] );
     229                                // Never cite something that is no longer public, even if a stale chunk survived.
     230                                if ( ! $post || 'publish' !== $post->post_status || '' !== $post->post_password ) {
     231                                        continue;
     232                                }
     233                                $sources[] = array(
     234                                        'title' => wp_strip_all_tags( get_the_title( $post ) ),
     235                                        'url'   => (string) get_permalink( $post ),
     236                                );
     237                        } else {
     238                                $sources[] = array(
     239                                        'title' => (string) $doc['title'],
     240                                        'url'   => '',
     241                                );
     242                        }
     243                }
     244                return $sources;
    162245        }
    163246
    … …  
    287370
    288371                if ( 'semantic' === $method ) {
     372                        $dims = count( $query_embedding );
    289373                        foreach ( $all_chunks as $chunk ) {
    290374                                $emb = json_decode( $chunk['embedding'], true );
    291                                 if ( ! is_array( $emb ) ) { continue; }
     375                                if ( ! is_array( $emb ) || count( $emb ) !== $dims ) { continue; }
    292376                                $scored[] = array(
    293377                                        'content' => $chunk['content'],
    … …  
    296380                                );
    297381                        }
    298                 } else {
     382                        if ( empty( $scored ) ) {
     383                                $method = 'keyword';
     384                        }
     385                }
     386
     387                if ( 'keyword' === $method ) {
    299388                        $words = array_filter( explode( ' ', mb_strtolower( $query ) ), function ( $w ) { return mb_strlen( $w ) > 2; } );
    300389                        $wc    = count( $words );
    … …  
    372461                EAIC_RAG_DB::delete_document_chunks( $doc_id );
    373462
    374                 $count = 0;
     463                // A chunk whose embedding failed is still stored (empty vector); keyword search finds it.
     464                $embeddings = $this->embed_many( $chunks );
     465                $count      = 0;
    375466                foreach ( $chunks as $i => $chunk ) {
    376                         $embedding = array();
    377                         try {
    378                                 $embedding = $this->get_embedding( $chunk );
    379                         } catch ( Exception $e ) {
    380                                 // Store chunk without embedding; keyword fallback handles search.
    381                                 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
    382                                 error_log( '[EAIC RAG] Chunk ' . $i . ' embedding failed: ' . $e->getMessage() );
    383                         }
    384                         $ok = EAIC_RAG_DB::add_chunk( $doc_id, $i, $chunk, wp_json_encode( $embedding ) );
     467                        $embedding = isset( $embeddings[ $i ] ) ? $embeddings[ $i ] : array();
     468                        $ok        = EAIC_RAG_DB::add_chunk( $doc_id, $i, $chunk, wp_json_encode( $embedding ) );
    385469                        if ( $ok ) {
    386470                                $count++;
    … …  
    399483
    400484                EAIC_RAG_DB::update_document_status( $doc_id, 'ready', $count );
     485                update_option( 'eaic_rag_embed_signature', $this->embed_signature(), false );
    401486
    402487                return $count;
    … …  
    408493
    409494        /**
    410          * Generate a text embedding vector via the Ollama embed API.
    411          *
    412          * Supports both the legacy /api/embeddings and current /api/embed endpoints.
     495         * Which service creates embeddings: 'ollama', 'openai' or 'gemini'.
     496         *
     497         * The default ('auto') follows the site's default chat provider, so someone who already
     498         * chats through OpenAI or Gemini gets semantic search without running an Ollama server,
     499         * while Ollama users keep exactly the behaviour they had before.
     500         *
     501         * @return string
     502         */
     503        public function embed_provider() {
     504                $choice = isset( $this->opts['rag_embed_provider'] ) ? (string) $this->opts['rag_embed_provider'] : 'auto';
     505                if ( in_array( $choice, array( 'ollama', 'openai', 'gemini' ), true ) ) {
     506                        return $choice;
     507                }
     508                $default = isset( $this->opts['default_provider'] ) ? (string) $this->opts['default_provider'] : 'ollama';
     509                if ( 'openai' === $default && '' !== trim( (string) ( $this->opts['openai_key'] ?? '' ) ) ) {
     510                        return 'openai';
     511                }
     512                if ( 'gemini' === $default && '' !== trim( (string) ( $this->opts['gemini_key'] ?? '' ) ) ) {
     513                        return 'gemini';
     514                }
     515                return 'ollama';
     516        }
     517
     518        /**
     519         * Identifier of the embedding model in use ("provider:model"). Vectors from different
     520         * models are not comparable, so this is stored alongside the index and compared later.
     521         *
     522         * @return string
     523         */
     524        public function embed_signature() {
     525                $provider = $this->embed_provider();
     526                if ( 'openai' === $provider || 'gemini' === $provider ) {
     527                        return $provider . ':' . $this->cloud_embed_model( $provider );
     528                }
     529                return 'ollama:' . ( ! empty( $this->opts['rag_embed_model'] ) ? $this->opts['rag_embed_model'] : 'nomic-embed-text' );
     530        }
     531
     532        /**
     533         * Embedding model for a cloud provider (filterable).
     534         *
     535         * @param string $provider 'openai' or 'gemini'.
     536         * @return string
     537         */
     538        private function cloud_embed_model( $provider ) {
     539                $default = 'openai' === $provider ? 'text-embedding-3-small' : 'gemini-embedding-001';
     540                return (string) apply_filters( 'eaic_embed_model', $default, $provider );
     541        }
     542
     543        /**
     544         * Generate a text embedding vector with the configured embedding service.
    413545         *
    414546         * @param string $text Text to embed.
    … …  
    417549         */
    418550        public function get_embedding( $text ) {
     551                if ( 'ollama' === $this->embed_provider() ) {
     552                        return $this->embed_ollama( $text );
     553                }
     554                $vectors = $this->embed_cloud_batch( array( (string) $text ) );
     555                return $vectors[0];
     556        }
     557
     558        /**
     559         * Embed many texts at once. A failed text yields an empty vector (it is still stored and
     560         * found by keyword search) instead of aborting the whole document.
     561         *
     562         * @param string[] $texts Texts keyed by index.
     563         * @return array<int|string,float[]>
     564         */
     565        public function embed_many( array $texts ) {
     566                $out = array();
     567                if ( 'ollama' === $this->embed_provider() ) {
     568                        foreach ( $texts as $i => $text ) {
     569                                try {
     570                                        $out[ $i ] = $this->embed_ollama( $text );
     571                                } catch ( Exception $e ) {
     572                                        $out[ $i ] = array();
     573                                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     574                                        error_log( '[EAIC RAG] Chunk ' . $i . ' embedding failed: ' . $e->getMessage() );
     575                                }
     576                        }
     577                        return $out;
     578                }
     579
     580                foreach ( array_chunk( array_keys( $texts ), 50 ) as $group ) {
     581                        $batch = array();
     582                        foreach ( $group as $k ) {
     583                                $batch[] = (string) $texts[ $k ];
     584                        }
     585                        try {
     586                                $vectors = $this->embed_cloud_batch( $batch );
     587                                foreach ( $group as $n => $k ) {
     588                                        $out[ $k ] = $vectors[ $n ];
     589                                }
     590                        } catch ( Exception $e ) {
     591                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
     592                                error_log( '[EAIC RAG] Batch embedding failed: ' . $e->getMessage() );
     593                                foreach ( $group as $k ) {
     594                                        $out[ $k ] = array();
     595                                }
     596                        }
     597                }
     598                return $out;
     599        }
     600
     601        /**
     602         * Embed up to ~100 texts with OpenAI or Gemini in a single request.
     603         *
     604         * @param string[] $batch Texts (sequential keys).
     605         * @return float[][] One vector per text, same order.
     606         * @throws RuntimeException On missing key, API error or malformed response.
     607         */
     608        private function embed_cloud_batch( array $batch ) {
     609                $provider = $this->embed_provider();
     610                $model    = $this->cloud_embed_model( $provider );
     611
     612                if ( 'openai' === $provider ) {
     613                        $key = trim( (string) ( $this->opts['openai_key'] ?? '' ) );
     614                        if ( '' === $key ) {
     615                                throw new RuntimeException( esc_html__( 'OpenAI API key is required for OpenAI embeddings.', 'easyit-ai-chat' ) );
     616                        }
     617                        $url     = 'https://api.openai.com/v1/embeddings';
     618                        $headers = array( 'Authorization' => 'Bearer ' . $key );
     619                        $body    = array( 'model' => $model, 'input' => array_values( $batch ) );
     620                } else {
     621                        $key = trim( (string) ( $this->opts['gemini_key'] ?? '' ) );
     622                        if ( '' === $key ) {
     623                                throw new RuntimeException( esc_html__( 'Gemini API key is required for Gemini embeddings.', 'easyit-ai-chat' ) );
     624                        }
     625                        $url      = 'https://generativelanguage.googleapis.com/v1beta/models/' . rawurlencode( $model ) . ':batchEmbedContents';
     626                        $headers  = array( 'x-goog-api-key' => $key );
     627                        $requests = array();
     628                        foreach ( $batch as $text ) {
     629                                $requests[] = array(
     630                                        'model'                => 'models/' . $model,
     631                                        'content'              => array( 'parts' => array( array( 'text' => $text ) ) ),
     632                                        'outputDimensionality' => 768, // Keeps stored vectors compact; plenty for site search.
     633                                );
     634                        }
     635                        $body = array( 'requests' => $requests );
     636                }
     637
     638                $response = wp_remote_post(
     639                        $url,
     640                        array(
     641                                'headers' => array_merge( array( 'Content-Type' => 'application/json' ), $headers ),
     642                                'body'    => wp_json_encode( $body ),
     643                                'timeout' => 30,
     644                        )
     645                );
     646                if ( is_wp_error( $response ) ) {
     647                        throw new RuntimeException( esc_html( $response->get_error_message() ) );
     648                }
     649                $code = (int) wp_remote_retrieve_response_code( $response );
     650                $data = json_decode( wp_remote_retrieve_body( $response ), true );
     651                if ( $code >= 400 || ! is_array( $data ) ) {
     652                        $msg = is_array( $data ) && isset( $data['error']['message'] ) ? (string) $data['error']['message'] : 'HTTP ' . $code;
     653                        throw new RuntimeException( esc_html( $msg ) );
     654                }
     655
     656                $vectors = array();
     657                if ( 'openai' === $provider ) {
     658                        $rows = isset( $data['data'] ) && is_array( $data['data'] ) ? $data['data'] : array();
     659                        usort( $rows, function ( $a, $b ) {
     660                                return ( $a['index'] ?? 0 ) <=> ( $b['index'] ?? 0 );
     661                        } );
     662                        foreach ( $rows as $row ) {
     663                                $vectors[] = isset( $row['embedding'] ) ? array_map( 'floatval', (array) $row['embedding'] ) : array();
     664                        }
     665                } else {
     666                        foreach ( (array) ( $data['embeddings'] ?? array() ) as $row ) {
     667                                $vectors[] = isset( $row['values'] ) ? array_map( 'floatval', (array) $row['values'] ) : array();
     668                        }
     669                }
     670
     671                if ( count( $vectors ) !== count( $batch ) || in_array( array(), $vectors, true ) ) {
     672                        throw new RuntimeException( esc_html__( 'The embedding service returned an unexpected response.', 'easyit-ai-chat' ) );
     673                }
     674                return $vectors;
     675        }
     676
     677        /**
     678         * Generate a text embedding vector via the Ollama embed API.
     679         *
     680         * Supports both the legacy /api/embeddings and current /api/embed endpoints.
     681         *
     682         * @param string $text Text to embed.
     683         * @return float[]
     684         * @throws RuntimeException On API or format error.
     685         */
     686        private function embed_ollama( $text ) {
     687                // If Ollama just failed, don't make every chat message (or every chunk of a bulk
     688                // re-index) wait on a dead server again — go straight to keyword search for a minute.
     689                if ( get_transient( 'eaic_embed_ollama_down' ) ) {
     690                        throw new RuntimeException( esc_html__( 'Ollama embeddings are temporarily unavailable.', 'easyit-ai-chat' ) );
     691                }
     692                try {
     693                        return $this->embed_ollama_request( $text );
     694                } catch ( RuntimeException $e ) {
     695                        set_transient( 'eaic_embed_ollama_down', 1, MINUTE_IN_SECONDS );
     696                        throw $e;
     697                }
     698        }
     699
     700        /**
     701         * Perform the Ollama embedding HTTP request.
     702         *
     703         * @param string $text Text to embed.
     704         * @return float[]
     705         * @throws RuntimeException On API or format error.
     706         */
     707        private function embed_ollama_request( $text ) {
    419708                $ollama_url = rtrim( ! empty( $this->opts['ollama_url'] ) ? $this->opts['ollama_url'] : 'http://localhost:11434', '/' );
    420709                $model      = ! empty( $this->opts['rag_embed_model'] ) ? $this->opts['rag_embed_model'] : 'nomic-embed-text';
  • easyit-ai-chat/trunk/includes/providers/class-eaic-anthropic.php

    r3617603 r3741982  
    2121
    2222        /**
    23          * Send a chat request.
     23         * Build the request body, headers and timeout shared by chat() and stream_chat().
    2424         *
    2525         * @param array  $messages Messages.
    2626         * @param string $system   System prompt.
    27          * @return string
     27         * @return array{0:array,1:array,2:int}
    2828         */
    29         public function chat( array $messages, $system = '' ) {
     29        private function build_request( array $messages, $system ) {
    3030                $key     = isset( $this->opts['anthropic_key'] ) ? $this->opts['anthropic_key'] : '';
    3131                $this->require_api_key( $key, 'Anthropic' );
    … …  
    7070                }
    7171
    72                 $data = $this->http_post(
     72                $headers = array(
     73                        'x-api-key'         => $key,
     74                        'anthropic-version' => '2023-06-01',
     75                );
     76
     77                return array( $body, $headers, $timeout );
     78        }
     79
     80        /**
     81         * Send a chat request.
     82         *
     83         * @param array  $messages Messages.
     84         * @param string $system   System prompt.
     85         * @return string
     86         */
     87        public function chat( array $messages, $system = '' ) {
     88                list( $body, $headers, $timeout ) = $this->build_request( $messages, $system );
     89
     90                $data = $this->http_post( 'https://api.anthropic.com/v1/messages', $body, $headers, $timeout );
     91
     92                $this->set_usage( $data['usage']['input_tokens'] ?? 0, $data['usage']['output_tokens'] ?? 0 );
     93
     94                return isset( $data['content'][0]['text'] ) ? (string) $data['content'][0]['text'] : '';
     95        }
     96
     97        /**
     98         * Stream a chat request token by token (Messages API server-sent events).
     99         *
     100         * @param array  $messages Messages.
     101         * @param string $system   System prompt.
     102         * @return string Full reply.
     103         */
     104        public function stream_chat( array $messages, $system = '' ) {
     105                if ( ! $this->can_stream() ) {
     106                        return parent::stream_chat( $messages, $system );
     107                }
     108                list( $body, $headers, $timeout ) = $this->build_request( $messages, $system );
     109                $body['stream'] = true;
     110
     111                $full_reply = '';
     112                $in_tokens  = 0;
     113                $out_tokens = 0;
     114
     115                $this->http_stream(
    73116                        'https://api.anthropic.com/v1/messages',
    74117                        $body,
    75                         array(
    76                                 'x-api-key'         => $key,
    77                                 'anthropic-version' => '2023-06-01',
    78                         ),
    79                         $timeout
     118                        $headers,
     119                        max( 60, $timeout ),
     120                        function ( $line ) use ( &$full_reply, &$in_tokens, &$out_tokens ) {
     121                                if ( 0 !== strpos( $line, 'data:' ) ) {
     122                                        return;
     123                                }
     124                                $chunk = json_decode( trim( substr( $line, 5 ) ), true );
     125                                if ( ! is_array( $chunk ) ) {
     126                                        return;
     127                                }
     128                                switch ( isset( $chunk['type'] ) ? $chunk['type'] : '' ) {
     129                                        case 'message_start':
     130                                                $in_tokens  = (int) ( $chunk['message']['usage']['input_tokens'] ?? 0 );
     131                                                $out_tokens = (int) ( $chunk['message']['usage']['output_tokens'] ?? 0 );
     132                                                break;
     133                                        case 'content_block_delta':
     134                                                $text = isset( $chunk['delta']['text'] ) ? (string) $chunk['delta']['text'] : '';
     135                                                if ( '' !== $text ) {
     136                                                        $full_reply .= $text;
     137                                                        self::sse_send( 'chunk', array( 'text' => $text ) );
     138                                                }
     139                                                break;
     140                                        case 'message_delta':
     141                                                $out_tokens = (int) ( $chunk['usage']['output_tokens'] ?? $out_tokens );
     142                                                break;
     143                                        case 'error':
     144                                                $message = isset( $chunk['error']['message'] ) ? (string) $chunk['error']['message'] : 'Anthropic streaming error';
     145                                                throw new RuntimeException( esc_html( $message ) );
     146                                }
     147                        }
    80148                );
    81149
    82                 return isset( $data['content'][0]['text'] ) ? (string) $data['content'][0]['text'] : '';
     150                $this->set_usage( $in_tokens, $out_tokens );
     151
     152                return $full_reply;
    83153        }
    84154
  • easyit-ai-chat/trunk/includes/providers/class-eaic-custom.php

    r3558390 r3741982  
    6767                );
    6868
     69                $this->set_usage( $data['usage']['prompt_tokens'] ?? 0, $data['usage']['completion_tokens'] ?? 0 );
     70
    6971                return isset( $data['choices'][0]['message']['content'] )
    7072                        ? (string) $data['choices'][0]['message']['content']
    … …  
    7779         * @return bool
    7880         */
     81        /**
     82         * Stream a chat request token by token (OpenAI-compatible endpoints).
     83         *
     84         * @param array  $messages Messages.
     85         * @param string $system   System prompt.
     86         * @return string Full reply.
     87         */
     88        public function stream_chat( array $messages, $system = '' ) {
     89                $url = rtrim( isset( $this->config['url'] ) ? $this->config['url'] : '', '/' );
     90                if ( ! $this->can_stream() || empty( $url ) ) {
     91                        return parent::stream_chat( $messages, $system );
     92                }
     93                $key     = isset( $this->config['api_key'] ) ? $this->config['api_key'] : '';
     94                $timeout = isset( $this->config['timeout'] ) ? max( 60, (int) $this->config['timeout'] ) : 60;
     95
     96                return $this->stream_openai_format(
     97                        $url . '/chat/completions',
     98                        array(
     99                                'model'       => isset( $this->config['model'] ) ? $this->config['model'] : '',
     100                                'messages'    => $this->plain_messages( $messages, $system ),
     101                                'max_tokens'  => 1000,
     102                                'temperature' => 0.7,
     103                        ),
     104                        array( 'Authorization' => 'Bearer ' . $key ),
     105                        $timeout,
     106                        false // Unknown gateways may reject `stream_options`; usage is estimated instead.
     107                );
     108        }
     109
    79110        public function health() {
    80111                $url = rtrim( isset( $this->config['url'] ) ? $this->config['url'] : '', '/' );
  • easyit-ai-chat/trunk/includes/providers/class-eaic-deepseek.php

    r3551548 r3741982  
    4949                );
    5050
     51                $this->set_usage( $data['usage']['prompt_tokens'] ?? 0, $data['usage']['completion_tokens'] ?? 0 );
     52
    5153                return isset( $data['choices'][0]['message']['content'] ) ? (string) $data['choices'][0]['message']['content'] : '';
    5254        }
    … …  
    5759         * @return bool
    5860         */
     61        /**
     62         * Stream a chat request token by token.
     63         *
     64         * @param array  $messages Messages.
     65         * @param string $system   System prompt.
     66         * @return string Full reply.
     67         */
     68        public function stream_chat( array $messages, $system = '' ) {
     69                if ( ! $this->can_stream() ) {
     70                        return parent::stream_chat( $messages, $system );
     71                }
     72                $key = isset( $this->opts['deepseek_key'] ) ? $this->opts['deepseek_key'] : '';
     73                $this->require_api_key( $key, 'DeepSeek' );
     74
     75                return $this->stream_openai_format(
     76                        'https://api.deepseek.com/v1/chat/completions',
     77                        array(
     78                                'model'       => ! empty( $this->opts['deepseek_model'] ) ? $this->opts['deepseek_model'] : 'deepseek-chat',
     79                                'messages'    => $this->plain_messages( $messages, $system ),
     80                                'max_tokens'  => isset( $this->opts['max_tokens'] ) ? (int) $this->opts['max_tokens'] : 1000,
     81                                'temperature' => isset( $this->opts['temperature'] ) ? (float) $this->opts['temperature'] : 0.7,
     82                        ),
     83                        array( 'Authorization' => 'Bearer ' . $key ),
     84                        isset( $this->opts['deepseek_timeout'] ) ? max( 60, (int) $this->opts['deepseek_timeout'] ) : 60
     85                );
     86        }
     87
    5988        public function health() {
    6089                try {
  • easyit-ai-chat/trunk/includes/providers/class-eaic-gemini.php

    r3617603 r3741982  
    3030         * @return string
    3131         */
    32         public function chat( array $messages, $system = '' ) {
     32        private function build_request( array $messages, $system ) {
    3333                $key     = isset( $this->opts['gemini_key'] )     ? $this->opts['gemini_key']     : '';
    3434                $model   = ! empty( $this->opts['gemini_model'] ) ? $this->opts['gemini_model']   : 'gemini-1.5-flash';
    … …  
    7171                }
    7272
     73                return array( $body, $model, $key, $timeout );
     74        }
     75
     76        /**
     77         * Send a chat request.
     78         *
     79         * @param array  $messages Messages.
     80         * @param string $system   System prompt.
     81         * @return string
     82         */
     83        public function chat( array $messages, $system = '' ) {
     84                list( $body, $model, $key, $timeout ) = $this->build_request( $messages, $system );
     85
    7386                $url  = self::BASE_URL . rawurlencode( $model ) . ':generateContent?key=' . rawurlencode( $key );
    7487                $data = $this->gemini_post( $url, $body, $timeout );
     88
     89                $this->set_usage( $data['usageMetadata']['promptTokenCount'] ?? 0, $data['usageMetadata']['candidatesTokenCount'] ?? 0 );
    7590
    7691                return isset( $data['candidates'][0]['content']['parts'][0]['text'] )
    … …  
    8499         * @return bool
    85100         */
     101        /**
     102         * Stream a chat request token by token (streamGenerateContent with SSE).
     103         *
     104         * @param array  $messages Messages.
     105         * @param string $system   System prompt.
     106         * @return string Full reply.
     107         */
     108        public function stream_chat( array $messages, $system = '' ) {
     109                if ( ! $this->can_stream() ) {
     110                        return parent::stream_chat( $messages, $system );
     111                }
     112                list( $body, $model, $key, $timeout ) = $this->build_request( $messages, $system );
     113
     114                $full_reply = '';
     115                $in_tokens  = 0;
     116                $out_tokens = 0;
     117
     118                $this->http_stream(
     119                        self::BASE_URL . rawurlencode( $model ) . ':streamGenerateContent?alt=sse',
     120                        $body,
     121                        array( 'x-goog-api-key' => $key ),
     122                        max( 60, $timeout ),
     123                        function ( $line ) use ( &$full_reply, &$in_tokens, &$out_tokens ) {
     124                                if ( 0 !== strpos( $line, 'data:' ) ) {
     125                                        return;
     126                                }
     127                                $chunk = json_decode( trim( substr( $line, 5 ) ), true );
     128                                if ( ! is_array( $chunk ) ) {
     129                                        return;
     130                                }
     131                                if ( ! empty( $chunk['usageMetadata'] ) ) {
     132                                        $in_tokens  = (int) ( $chunk['usageMetadata']['promptTokenCount'] ?? $in_tokens );
     133                                        $out_tokens = (int) ( $chunk['usageMetadata']['candidatesTokenCount'] ?? $out_tokens );
     134                                }
     135                                $parts = isset( $chunk['candidates'][0]['content']['parts'] ) ? (array) $chunk['candidates'][0]['content']['parts'] : array();
     136                                foreach ( $parts as $part ) {
     137                                        // Skip "thinking" parts; only the visible answer is shown.
     138                                        if ( ! empty( $part['thought'] ) || empty( $part['text'] ) ) {
     139                                                continue;
     140                                        }
     141                                        $text        = (string) $part['text'];
     142                                        $full_reply .= $text;
     143                                        self::sse_send( 'chunk', array( 'text' => $text ) );
     144                                }
     145                        }
     146                );
     147
     148                $this->set_usage( $in_tokens, $out_tokens );
     149
     150                return $full_reply;
     151        }
     152
    86153        public function health() {
    87154                try {
  • easyit-ai-chat/trunk/includes/providers/class-eaic-ollama.php

    r3562625 r3741982  
    5050                        function ( $line ) use ( &$full_reply ) {
    5151                                $data  = json_decode( $line, true );
     52                                if ( ! empty( $data['done'] ) ) {
     53                                        $this->set_usage( $data['prompt_eval_count'] ?? 0, $data['eval_count'] ?? 0 );
     54                                }
    5255                                $chunk = isset( $data['message']['content'] ) ? (string) $data['message']['content'] : '';
    5356                                if ( '' !== $chunk ) {
    … …  
    9396                );
    9497
     98                $this->set_usage( $data['prompt_eval_count'] ?? 0, $data['eval_count'] ?? 0 );
     99
    95100                return isset( $data['message']['content'] ) ? (string) $data['message']['content'] : '';
    96101        }
  • easyit-ai-chat/trunk/includes/providers/class-eaic-openai.php

    r3617603 r3741982  
    1717
    1818        /**
    19          * Send a chat request.
     19         * Build the request body, headers and timeout shared by chat() and stream_chat().
    2020         *
    2121         * @param array  $messages Messages.
    2222         * @param string $system   System prompt.
    23          * @return string
     23         * @return array{0:array,1:array,2:int}
    2424         */
    25         public function chat( array $messages, $system = '' ) {
     25        private function build_request( array $messages, $system ) {
    2626                $key     = isset( $this->opts['openai_key'] ) ? $this->opts['openai_key'] : '';
    2727                $this->require_api_key( $key, 'OpenAI' );
    … …  
    5050                }
    5151
    52                 $data = $this->http_post(
    53                         'https://api.openai.com/v1/chat/completions',
    54                         array(
    55                                 'model'       => $model,
    56                                 'messages'    => $payload_messages,
    57                                 'max_tokens'  => isset( $this->opts['max_tokens'] ) ? (int) $this->opts['max_tokens'] : 1000,
    58                                 'temperature' => isset( $this->opts['temperature'] ) ? (float) $this->opts['temperature'] : 0.7,
    59                         ),
    60                         array( 'Authorization' => 'Bearer ' . $key ),
    61                         $timeout
     52                $body = array(
     53                        'model'       => $model,
     54                        'messages'    => $payload_messages,
     55                        'max_tokens'  => isset( $this->opts['max_tokens'] ) ? (int) $this->opts['max_tokens'] : 1000,
     56                        'temperature' => isset( $this->opts['temperature'] ) ? (float) $this->opts['temperature'] : 0.7,
    6257                );
    6358
     59                return array( $body, array( 'Authorization' => 'Bearer ' . $key ), $timeout );
     60        }
     61
     62        /**
     63         * Send a chat request.
     64         *
     65         * @param array  $messages Messages.
     66         * @param string $system   System prompt.
     67         * @return string
     68         */
     69        public function chat( array $messages, $system = '' ) {
     70                list( $body, $headers, $timeout ) = $this->build_request( $messages, $system );
     71
     72                $data = $this->http_post( 'https://api.openai.com/v1/chat/completions', $body, $headers, $timeout );
     73
     74                $this->set_usage( $data['usage']['prompt_tokens'] ?? 0, $data['usage']['completion_tokens'] ?? 0 );
     75
    6476                return isset( $data['choices'][0]['message']['content'] ) ? (string) $data['choices'][0]['message']['content'] : '';
     77        }
     78
     79        /**
     80         * Stream a chat request token by token.
     81         *
     82         * @param array  $messages Messages.
     83         * @param string $system   System prompt.
     84         * @return string Full reply.
     85         */
     86        public function stream_chat( array $messages, $system = '' ) {
     87                if ( ! $this->can_stream() ) {
     88                        return parent::stream_chat( $messages, $system );
     89                }
     90                list( $body, $headers, $timeout ) = $this->build_request( $messages, $system );
     91
     92                return $this->stream_openai_format( 'https://api.openai.com/v1/chat/completions', $body, $headers, max( 60, $timeout ) );
    6593        }
    6694
  • easyit-ai-chat/trunk/includes/providers/class-eaic-together.php

    r3617353 r3741982  
    5252                        $timeout
    5353                );
     54
     55                $this->set_usage( $data['usage']['prompt_tokens'] ?? 0, $data['usage']['completion_tokens'] ?? 0 );
    5456
    5557                return isset( $data['choices'][0]['message']['content'] ) ? (string) $data['choices'][0]['message']['content'] : '';
  • easyit-ai-chat/trunk/public/class-eaic-public.php

    r3617603 r3741982  
    9494                                        0, 6
    9595                                ),
     96                                'lead_main_enabled'           => (bool) $opts['lead_main_enabled'],
     97                                'lead_nonce'                  => wp_create_nonce( 'eaic_save_lead' ),
     98                                'lead_title'                  => $opts['lead_form_title'],
     99                                'lead_sub'                    => $opts['lead_form_sub'],
    96100                                'upload_max_image_mb'         => max( 1, (int) $opts['attachments_upload_max_image_mb'] ),
    97101                                'upload_max_doc_mb'           => max( 1, (int) $opts['attachments_upload_max_doc_mb'] ),
  • easyit-ai-chat/trunk/public/css/chat.css

    r3617603 r3741982  
    642642.eaic-widget .eaic-fb-btn.eaic-fb-active { opacity:1 !important; border-color:var(--c-accent) !important; background:rgba(79,70,229,.07) !important; }
    643643
     644/* ---- Lead capture card ---- */
     645.eaic-widget .eaic-lead-card {
     646        margin:        12px 0 !important;
     647        padding:       14px !important;
     648        border:        1px solid var(--c-border) !important;
     649        border-radius: 12px !important;
     650        background:    rgba(79,70,229,.04) !important;
     651        display:       flex !important;
     652        flex-direction:column !important;
     653        gap:           8px !important;
     654        max-width:     340px !important;
     655}
     656.eaic-widget .eaic-lead-card-title { font-weight:600 !important; font-size:14px !important; }
     657.eaic-widget .eaic-lead-card-sub   { font-size:12px !important; opacity:.7 !important; }
     658.eaic-widget .eaic-lead-card input {
     659        padding:       8px 10px !important;
     660        border:        1px solid var(--c-border) !important;
     661        border-radius: 8px !important;
     662        font-size:     13px !important;
     663        background:    transparent !important;
     664        color:         inherit !important;
     665}
     666.eaic-widget .eaic-lead-card input.eaic-invalid { border-color:#d63638 !important; }
     667.eaic-widget .eaic-lead-card-actions { display:flex !important; gap:8px !important; align-items:center !important; }
     668.eaic-widget .eaic-lead-card-save {
     669        padding:       7px 14px !important;
     670        border:        0 !important;
     671        border-radius: 8px !important;
     672        background:    var(--c-accent) !important;
     673        color:         #fff !important;
     674        cursor:        pointer !important;
     675        font-size:     13px !important;
     676}
     677.eaic-widget .eaic-lead-card-skip {
     678        padding:    7px 10px !important;
     679        border:     0 !important;
     680        background: transparent !important;
     681        cursor:     pointer !important;
     682        font-size:  12px !important;
     683        opacity:    .7 !important;
     684        color:      inherit !important;
     685}
     686
     687/* ---- Source citations ---- */
     688.eaic-widget .eaic-sources {
     689        display:     flex !important;
     690        flex-wrap:   wrap !important;
     691        align-items: center !important;
     692        gap:         6px !important;
     693        margin-top:  8px !important;
     694        font-size:   12px !important;
     695}
     696.eaic-widget .eaic-sources-label { opacity:.65 !important; }
     697.eaic-widget .eaic-source {
     698        display:         inline-block !important;
     699        max-width:       100% !important;
     700        padding:         2px 8px !important;
     701        border:          1px solid var(--c-border) !important;
     702        border-radius:   999px !important;
     703        color:           inherit !important;
     704        text-decoration: none !important;
     705        overflow:        hidden !important;
     706        text-overflow:   ellipsis !important;
     707        white-space:     nowrap !important;
     708}
     709.eaic-widget a.eaic-source { color:var(--c-accent) !important; }
     710.eaic-widget a.eaic-source:hover { background:rgba(79,70,229,.07) !important; text-decoration:underline !important; }
     711
    644712/* ---- Message action bar (Copy + Download) ---- */
    645713.eaic-widget .eaic-msg-actions {
  • easyit-ai-chat/trunk/public/js/chat.js

    r3617603 r3741982  
    580580                var contentEl    = null;
    581581                var sessionSaved = false;
     582                var sourcesData  = null;
    582583
    583584                fetch( CFG.ajax_url, {
    … …  
    650651                                                        }
    651652
     653                                                        if ( 'sources' === eventName && json.sources ) {
     654                                                                sourcesData = json.sources;
     655                                                        }
     656
    652657                                                        if ( 'done' === eventName ) {
    653658                                                                self.clearTimer();
    … …  
    664669                                                                        self.appendRegenBtn( doneMsg );
    665670                                                                        var doneBody = doneMsg ? doneMsg.querySelector( '.eaic-msg-body' ) : null;
     671                                                                        var doneSrc  = buildSources( sourcesData );
     672                                                                        if ( doneSrc && doneBody ) { contentEl.parentNode.insertBefore( doneSrc, contentEl.nextSibling ); }
    666673                                                                        self.appendMsgActions( doneBody, contentEl );
    667674                                                                }
    … …  
    934941        }
    935942
     943        /**
     944         * Build the "Sources" list shown under answers drawn from site content / documents.
     945         * Only http(s) URLs are linked; uploaded documents (no URL) are shown as plain text.
     946         */
     947        function buildSources( sources ) {
     948                if ( ! sources || ! sources.length ) { return null; }
     949                var wrap = document.createElement( 'div' );
     950                wrap.className = 'eaic-sources';
     951                var label = document.createElement( 'span' );
     952                label.className   = 'eaic-sources-label';
     953                label.textContent = t( 'sources', 'Sources' ) + ':';
     954                wrap.appendChild( label );
     955                sources.forEach( function ( s ) {
     956                        if ( ! s || ! s.title ) { return; }
     957                        var item;
     958                        if ( s.url && /^https?:\/\//i.test( s.url ) ) {
     959                                item = document.createElement( 'a' );
     960                                item.href   = s.url;
     961                                item.target = '_blank';
     962                                item.rel    = 'noopener noreferrer';
     963                        } else {
     964                                item = document.createElement( 'span' );
     965                        }
     966                        item.className   = 'eaic-source';
     967                        item.textContent = s.title;
     968                        wrap.appendChild( item );
     969                } );
     970                return wrap.children.length > 1 ? wrap : null;
     971        }
     972
    936973        Widget.prototype.appendMessage = function ( role, content, opts ) {
    937974                if ( ! this.elMessages ) { return null; }
    … …  
    9921029                body.appendChild( label );
    9931030                body.appendChild( content_el );
     1031
     1032                if ( 'assistant' === role && opts.sources ) {
     1033                        var srcEl = buildSources( opts.sources );
     1034                        if ( srcEl ) { body.appendChild( srcEl ); }
     1035                }
    9941036
    9951037                // Feedback 👍👎 on assistant messages.
    … …  
    10641106                this.elMessages.appendChild( w );
    10651107                this.appendWelcomeBubble();
     1108                this.showLeadCard();
    10661109                this.renderSuggestedQuestions();
     1110        };
     1111
     1112        /**
     1113         * Optional, skippable "name + email" card at the top of a new chat. Shown once per browser:
     1114         * submitting or skipping it remembers the choice in localStorage.
     1115         */
     1116        Widget.prototype.showLeadCard = function () {
     1117                if ( ! CFG.lead_main_enabled || ! CFG.lead_nonce || ! this.elMessages ) { return; }
     1118                if ( this.elMessages.querySelector( '.eaic-lead-card' ) ) { return; }
     1119                var storeKey = 'eaic_lead_main';
     1120                try { if ( window.localStorage.getItem( storeKey ) ) { return; } } catch ( e ) { /* storage blocked: show it */ }
     1121
     1122                var card = document.createElement( 'div' );
     1123                card.className = 'eaic-lead-card';
     1124
     1125                var title = document.createElement( 'div' );
     1126                title.className   = 'eaic-lead-card-title';
     1127                title.textContent = CFG.lead_title || t( 'lead_title', 'Quick intro' );
     1128
     1129                var sub = document.createElement( 'div' );
     1130                sub.className   = 'eaic-lead-card-sub';
     1131                sub.textContent = CFG.lead_sub || t( 'lead_sub', 'Optional — so we can follow up if needed' );
     1132
     1133                var name = document.createElement( 'input' );
     1134                name.type = 'text'; name.autocomplete = 'given-name'; name.maxLength = 100;
     1135                name.placeholder = t( 'lead_name', 'Your name' );
     1136
     1137                var email = document.createElement( 'input' );
     1138                email.type = 'email'; email.autocomplete = 'email'; email.maxLength = 200;
     1139                email.placeholder = t( 'lead_email', 'Email' );
     1140
     1141                var row = document.createElement( 'div' );
     1142                row.className = 'eaic-lead-card-actions';
     1143                var saveBtn = document.createElement( 'button' );
     1144                saveBtn.type = 'button'; saveBtn.className = 'eaic-lead-card-save';
     1145                saveBtn.textContent = t( 'lead_save', 'Continue' );
     1146                var skipBtn = document.createElement( 'button' );
     1147                skipBtn.type = 'button'; skipBtn.className = 'eaic-lead-card-skip';
     1148                skipBtn.textContent = t( 'lead_skip', 'Skip' );
     1149                row.appendChild( saveBtn );
     1150                row.appendChild( skipBtn );
     1151
     1152                card.appendChild( title );
     1153                card.appendChild( sub );
     1154                card.appendChild( name );
     1155                card.appendChild( email );
     1156                card.appendChild( row );
     1157
     1158                function remember() {
     1159                        try { window.localStorage.setItem( storeKey, '1' ); } catch ( e ) { /* ignore */ }
     1160                }
     1161                function dismiss() {
     1162                        remember();
     1163                        // Remove every copy on the page (floating widget + shortcode widget share the choice).
     1164                        Array.prototype.forEach.call( document.querySelectorAll( '.eaic-lead-card' ), function ( c ) {
     1165                                if ( c.parentNode ) { c.parentNode.removeChild( c ); }
     1166                        } );
     1167                }
     1168                function visitorId() {
     1169                        var id = '';
     1170                        try { id = window.localStorage.getItem( 'eaic_visitor_id' ) || ''; } catch ( e ) { /* ignore */ }
     1171                        if ( ! id ) {
     1172                                id = 'v' + Math.random().toString( 16 ).slice( 2, 14 ) + Date.now().toString( 16 );
     1173                                try { window.localStorage.setItem( 'eaic_visitor_id', id ); } catch ( e ) { /* ignore */ }
     1174                        }
     1175                        return id.slice( 0, 64 );
     1176                }
     1177
     1178                saveBtn.addEventListener( 'click', function () {
     1179                        var n = ( name.value || '' ).trim();
     1180                        var m = ( email.value || '' ).trim();
     1181                        if ( m && ! /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test( m ) ) {
     1182                                email.classList.add( 'eaic-invalid' );
     1183                                email.focus();
     1184                                return;
     1185                        }
     1186                        if ( ! n && ! m ) { dismiss(); return; }
     1187                        var body = new FormData();
     1188                        body.append( 'action', 'eaic_save_lead' );
     1189                        body.append( 'nonce', CFG.lead_nonce );
     1190                        body.append( 'session_id', visitorId() );
     1191                        body.append( 'name', n );
     1192                        body.append( 'email', m );
     1193                        body.append( 'context', 'chat' );
     1194                        fetch( CFG.ajax_url, { method: 'POST', body: body, credentials: 'same-origin' } ).catch( function () { /* best effort */ } );
     1195                        dismiss();
     1196                } );
     1197                skipBtn.addEventListener( 'click', dismiss );
     1198
     1199                this.elMessages.appendChild( card );
    10671200        };
    10681201
    … …  
    11081241                                ! self.elMessages.querySelector( '.eaic-suggested-chips' ) ) {
    11091242                                self.appendWelcomeBubble();
     1243                                self.showLeadCard();
    11101244                                self.renderSuggestedQuestions();
    11111245                        }
    … …  
    12161350                        var asstIdx = 0;
    12171351                        ( data.messages || [] ).forEach( function ( m ) {
    1218                                 var fbOpts = { provider: data.provider, created_at: m.created_at, attachments: m.attachments || [] };
     1352                                var fbOpts = { provider: data.provider, created_at: m.created_at, attachments: m.attachments || [], sources: m.sources || [] };
    12191353                                if ( 'assistant' === m.role ) {
    12201354                                        fbOpts.fb_index = asstIdx++;
    … …  
    13571491                var chips = this.elMessages && this.elMessages.querySelector( '.eaic-suggested-chips' );
    13581492                if ( chips && chips.parentNode ) { chips.parentNode.removeChild( chips ); }
     1493                var lead = this.elMessages && this.elMessages.querySelector( '.eaic-lead-card' );
     1494                if ( lead && lead.parentNode ) { lead.parentNode.removeChild( lead ); }
    13591495        };
    13601496
  • easyit-ai-chat/trunk/readme.txt

    r3617603 r3741982  
    55Tested up to: 7.0
    66Requires PHP: 8.0
    7 Stable tag: 2.7.0
     7Stable tag: 2.8.0
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    111111
    112112* **Document upload** — Upload PDF files to a private Knowledge Base; the AI answers questions using only your document data
    113 * **Semantic + keyword search** — Queries are matched against document chunks via Ollama embeddings with automatic keyword fallback
     113* **Semantic + keyword search** — Queries are matched against document chunks using embeddings from OpenAI, Google Gemini or a self-hosted Ollama server, with automatic keyword fallback
    114114* **Accurate counting** — "How many X" queries scan every chunk for an exact count — not just the top-K semantic results
    115115* **Context-aware answers** — Matched chunks are injected into the system prompt so the AI gives specific, document-grounded answers
    116116* **Admin test tool** — Test Query UI lets you inspect which chunks are retrieved for any query before going live
    117117* **Re-process on demand** — Change embedding model or chunk settings and reprocess any document without re-uploading
     118
     119= 📈 Insights, Cost Control & Leads (v2.8.0) =
     120
     121* **Source citations** — Answers drawn from your site content or documents show "Sources" links to the pages they came from, so visitors can verify and click through
     122* **Usage & cost tracking** — Tokens and estimated cost per day, provider and model on the Analytics page
     123* **Budget caps** — Set a daily/monthly token limit or a monthly cost limit; the chat pauses with your own message when it's reached, and you get one email
     124* **Knowledge gaps** — See the questions your chat couldn't answer from your content (and the answers visitors rated "not helpful"), so you know what to write next
     125* **Lead capture in the main chat** — Optional, skippable name + email card; email notification for each new lead and CSV export
     126* **Weekly summary email** — Opt-in digest of conversations, questions, AI cost, new leads and unanswered questions
     127* **Real-time streaming for every provider** — Replies now appear word by word with OpenAI, Claude, Gemini and DeepSeek too (previously only Ollama and Together AI)
    118128
    119129= 🌐 Ask This Site (v2.5.0) =
    … …  
    174184
    175185= OpenAI =
    176 Used when OpenAI is selected as the AI provider.
     186Used when OpenAI is selected as the AI provider, and for embeddings (to power semantic search over your site content or documents) when OpenAI is chosen as the embedding service. Text sent for embedding is the content you index.
    177187* Service URL: https://api.openai.com/
    178188* Terms of Use: https://openai.com/policies/row-terms-of-use
    … …  
    192202
    193203= Google Gemini =
    194 Used when Google Gemini is selected as the AI provider.
     204Used when Google Gemini is selected as the AI provider, and for embeddings (semantic search over your site content or documents) when Gemini is chosen as the embedding service.
    195205* Service URL: https://generativelanguage.googleapis.com/
    196206* Terms of Use: https://ai.google.dev/gemini-api/terms
    … …  
    314324
    315325== Changelog ==
     326
     327= 2.8.0 =
     328* New: **Source citations** — when an answer comes from your site content or Knowledge Base, the chat shows clickable "Sources" under it. Only published, public pages are ever linked.
     329* New: **Usage & cost tracking** — token usage and estimated cost per provider/model on the Analytics page, using the token counts the AI provider reports (estimated when a provider doesn't report them).
     330* New: **Budget caps** — daily token, monthly token and monthly cost limits. When one is reached the chat pauses with a message you choose and you receive a single email. Custom model prices can be entered for Together AI and custom providers.
     331* New: **Real streaming for OpenAI, Anthropic (Claude), Google Gemini, DeepSeek and custom OpenAI-compatible providers** — replies appear as they are generated instead of all at once.
     332* New: **Cloud embeddings** — Ask This Site and the Knowledge Base can now use OpenAI or Gemini embeddings for semantic search, so no Ollama server is needed. Choose the service under Knowledge Base → Embedding Service (default: follows your chat provider). Changing the embedding service means re-indexing; the page tells you when that's needed, and keyword search is used in the meantime.
     333* New: **Knowledge gaps report** on the Analytics page — questions with no match in your content, plus answers rated "not helpful".
     334* New: **Lead capture in the main chat** (opt-in), new-lead email notifications, and CSV export of leads.
     335* New: **Weekly summary email** (opt-in).
     336* Improvement: A short, one-time review request appears on this plugin's own admin pages after the chat has been used for a while; it can be dismissed permanently.
     337* Improvement: If the Ollama embedding server is unreachable, chat falls back to keyword search immediately instead of waiting on a timeout for every message.
     338* Fix: Saving the Knowledge Base page no longer blanks your AI provider API keys or unticks settings that live on the Settings page.
     339* Fix: The non-streaming chat endpoint now uses the Knowledge Base like the streaming one.
     340* Removed: The bundled Freemius SDK (about 23 MB). It was no longer used. The plugin makes no calls except to the AI provider you choose.
    316341
    317342= 2.7.0 =
    … …  
    499524== Upgrade Notice ==
    500525
     526= 2.8.0 =
     527New: source citations, usage & budget caps, real streaming for OpenAI/Claude/Gemini/DeepSeek, cloud embeddings, knowledge-gap report, lead capture & weekly summary. Also fixes the Knowledge Base page clearing API keys on save, and removes the unused Freemius SDK.
     528
    501529= 2.5.0 =
    502530New: Ask This Site — enable one toggle in Knowledge Base settings and the AI automatically learns your site's own posts/pages, no manual document upload needed.
  • easyit-ai-chat/trunk/uninstall.php

    r3617353 r3741982  
    2121$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}eaic_chunks" );
    2222$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}eaic_documents" );
     23$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}eaic_usage" );
     24$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}eaic_gaps" );
    2325// WooCommerce bots (merged in from Pro in v2.4.0).
    2426$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}eaic_order_chats" );
    … …  
    4244delete_option( 'eaic_options' );
    4345delete_option( 'eaic_db_version' );
     46delete_option( 'eaic_schema_rev' );
     47delete_option( 'eaic_first_seen' );
     48delete_option( 'eaic_rag_embed_signature' );
     49// Leftovers from the Freemius SDK that shipped before v2.8.0.
     50delete_option( 'fs_accounts' );
     51delete_option( 'fs_active_plugins' );
     52delete_option( 'fs_api_cache' );
     53delete_option( 'fs_debug_mode' );
    4454delete_option( 'eaic_order_db_version' );
    4555delete_option( 'eaic_product_db_version' );
Note: See TracChangeset for help on using the changeset viewer.