Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Adam-s-tech/e851354bf3cae8a07633ad39e42e90c0 to your computer and use it in GitHub Desktop.
Save Adam-s-tech/e851354bf3cae8a07633ad39e42e90c0 to your computer and use it in GitHub Desktop.

Revisions

  1. @charlesteh charlesteh revised this gist Dec 13, 2023. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions cf-workers-ai-bge-small.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    // Made by @charlestehio: https://x.com/charlestehio
    // Usage: https://abc.workers.dev/?query=your%20embedding%20query

    import { Ai } from './vendor/@cloudflare/ai.js';
  2. @charlesteh charlesteh revised this gist Dec 13, 2023. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions cf-workers-ai-bge-small.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    // Usage: https://abc.workers.dev/?query=your%20embedding%20query

    import { Ai } from './vendor/@cloudflare/ai.js';

    export default {
  3. @charlesteh charlesteh renamed this gist Dec 13, 2023. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. @charlesteh charlesteh created this gist Dec 13, 2023.
    32 changes: 32 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    import { Ai } from './vendor/@cloudflare/ai.js';

    export default {
    async fetch(request, env) {
    // Parse the URL to get query parameters
    const url = new URL(request.url);
    var query = url.searchParams.get('query');

    // Check if the query parameter exists and is not empty
    // If the query parameter does not exist or is empty, return {"response": null}
    if (!query) {
    return new Response(JSON.stringify({ response: null }), {
    status: 400,
    headers: { 'Content-Type': 'application/json' }
    });
    }

    // Clean the query using regex. This regex filters the query string to remove any characters
    // that are not letters (a-z, A-Z), numbers (0-9), whitespace (spaces, tabs, etc.), commas, or periods.
    // For example, if the input query is "Hello! How are you? #Cloudflare", the regex will remove
    // the exclamation mark (!), question mark (?), and hash (#), resulting in the cleaned query
    // "Hello How are you Cloudflare".
    query = query.replace(/[^a-zA-Z0-9\s,\.]/g, '').trim();

    const ai = new Ai(env.AI);
    const input = {
    text: `${query}`
    };
    const response = await ai.run('@cf/baai/bge-small-en-v1.5', input);
    return new Response(JSON.stringify({ response }), { headers: { 'Content-Type': 'application/json' } });
    }
    };