### Create Cloudflare Worker Project Source: https://context7_llms Initializes a new Cloudflare Worker project named `hello-ai` using the `create-cloudflare` CLI tool. This command will prompt for setup and install Wrangler, the Cloudflare Developer Platform CLI. ```bash npm create cloudflare@latest hello-ai ``` -------------------------------- ### Install Groq SDK via npm Source: https://www.npmjs.com/package/groq-sdk Instructions for installing the Groq SDK package using the npm package manager. ```npm npm install groq-sdk ``` -------------------------------- ### Install Groq SDK using npm Source: https://www.npmjs.com/package/groq-sdk This command installs the Groq SDK package into your project using npm, making it available for use in your JavaScript/TypeScript applications. ```Shell npm i groq-sdk ``` -------------------------------- ### Website Anti-Flicker and Initialization Scripts Source: https://www.anthropic.com/ This snippet includes various JavaScript and CSS configurations for website initialization, including font loading, touch detection, anti-flicker mechanisms, and Intellimize A/B testing integration. It ensures a smooth loading experience and proper tracking setup. ```javascript AnthropicWebFont.load({ google: { families: ["Fira Code:regular,500"] }});!function(o,c){var n=c.documentElement,t=" w-mod-";n.className+=t+"js",("ontouchstart"in o||o.DocumentTouch&&c instanceof DocumentTouch)&&(n.className+=t+"touch")}(window,document);if (localStorage.getItem('intellimize_data_tracking_type') !== 'disabled') { localStorage.setItem('intellimize_opt_out_117895469', 'true'); } if (localStorage.getItem('intellimize_data_tracking_type') !== 'disabled') { localStorage.setItem('intellimize_data_tracking_type', 'disabled'); }(function(e){var s={r:[]};e.wf={r:s.r,ready:t=>{s.r.push(t)}}})(window)(function(e,t,p){var n=document.documentElement,s={p:[],r:[]},u={p:s.p,r:s.r,push:function(e){s.p.push(e)},ready:function(e){s.r.push(e)}};e.intellimize=u,n.className+=" "+p,setTimeout(function(){n.className=n.className.replace(RegExp(" ?"+p),"")},t)})(window, 4000, 'anti-flicker')var wfClientScript=document.createElement("script");wfClientScript.src="https://cdn.intellimize.co/snippet/117895469.js",wfClientScript.async=!0,wfClientScript.onerror=function(){document.documentElement.className=document.documentElement.className.replace(RegExp(" ?anti-flicker"),"")},document.head.appendChild(wfClientScript); ``` ```css .anti-flicker, .anti-flicker * {visibility: hidden !important; opacity: 0 !important;}[data-wf-hidden-variation], [data-wf-hidden-variation] * { display: none !important; } ``` -------------------------------- ### JavaScript: Initialize Google Tag Manager Consent Defaults Source: https://www.anthropic.com/ Sets up the Google Tag Manager `dataLayer` and initializes default consent states based on user preferences. This ensures GTM respects user choices for ad personalization, user data, ad storage, and analytics storage from the start. ```JavaScript window.dataLayer = window.dataLayer || []; function gtag(){window.dataLayer.push(arguments);} gtag('consent', 'default', { 'ad_personalization': initialPreferences.marketing ? 'granted' : 'denied', 'ad_user_data': initialPreferences.marketing ? 'granted' : 'denied', 'ad_storage': initialPreferences.marketing ? 'granted' : 'denied', 'analytics_storage': initialPreferences.analytics ? 'granted' : 'denied', 'functionality_storage': 'granted', 'personalization_storage': 'granted', 'security_storage': 'granted' }); ``` -------------------------------- ### Install Cohere Python SDK Source: https://github.com/cohere-ai/cohere-python This command installs the Cohere Python SDK using pip, the standard Python package installer. Ensure you have pip installed and configured in your environment. ```Python pip install cohere ``` -------------------------------- ### JavaScript Example: Making Authenticated AWS Fetch Requests Source: https://github.com/mhart/aws4fetch This JavaScript example demonstrates how to initialize an `AwsClient` instance and then use its `fetch` method to send an authenticated request to an AWS service. It illustrates how to pass standard fetch options along with AWS-specific signing parameters, and how to process the response. ```JavaScript import { AwsClient } from 'aws4fetch' const aws = new AwsClient(opts) async function doFetch() { const response = await aws.fetch(url, { method, // if not supplied, will default to 'POST' if there's a body, otherwise 'GET' headers, // standard JS object literal, or Headers instance body, // optional, String or ArrayBuffer/ArrayBufferView – ie, remember to stringify your JSON // and any other standard fetch options, eg keepalive, etc // optional, largely if you want to override options in the AwsClient instance aws: { signQuery, // set to true to sign the query string instead of the Authorization header accessKeyId, // same as in AwsClient constructor above secretAccessKey, // same as in AwsClient constructor above sessionToken, // same as in AwsClient constructor above service, // same as in AwsClient constructor above region, // same as in AwsClient constructor above cache, // same as in AwsClient constructor above datetime, // defaults to now, to override use the form '20150830T123600Z' appendSessionToken, // set to true to add X-Amz-Security-Token after signing, defaults to true for iot allHeaders, // set to true to force all headers to be signed instead of the defaults singleEncode, // set to true to only encode %2F once (usually only needed for testing) }, }) console.log(await response.json()) } ``` -------------------------------- ### Example Response for AI Gateway Logs GET Request Source: https://context7_llms Provides an example of the JSON structure returned when querying AI Gateway logs via the Cloudflare API, highlighting the `id` field for each log entry. ```json { "result": [ { "id": "01JADMCQQQBWH3NXZ5GCRN98DP", "cached": true, "created_at": "2019-08-24T14:15:22Z", "custom_cost": true, "duration": 0, "id": "string", "metadata": "string", "model": "string", "model_type": "string", "path": "string", "provider": "string", "request_content_type": "string", "request_type": "string", "response_content_type": "string", "status_code": 0, "step": 0, "success": true, "tokens_in": 0, "tokens_out": 0 } ], "result_info": { "count": 0, "max_cost": 0, "max_duration": 0, "max_tokens_in": 0, "max_tokens_out": 0, "max_total_tokens": 0, "min_cost": 0, "min_duration": 0, "min_tokens_in": 0, "min_tokens_out": 0, "min_total_tokens": 0, "page": 0, "per_page": 0, "total_count": 0 }, "success": true } ``` -------------------------------- ### Install aws4fetch via npm Source: https://github.com/mhart/aws4fetch Instructions to install the `aws4fetch` package using the npm package manager, making it available for use in JavaScript projects. ```npm npm install aws4fetch ``` -------------------------------- ### Initiate Model Training/Fine-tuning on Replicate (Python) Source: https://replicate.com/ This code shows how to start a model training job on Replicate. It specifies the destination for the new model, the base version to fine-tune, and training-specific inputs like steps, input images, and a trigger word. ```Python training = replicate.trainings.create( destination="mattrothenberg/drone-art" version="ostris/flux-dev-lora-trainer:e440909d3512c31646ee2e0c7d6f6f4923224863a6a10c494606e79fb5844497", input={ "steps": 1000, "input_images": https://example.com/images.zip , "trigger_word": "TOK", }, ) ``` -------------------------------- ### Example: Using AwsV4Signer to Sign a Request Source: https://github.com/mhart/aws4fetch Demonstrates how to import `AwsV4Signer`, initialize it with options, and use the `sign()` method to obtain signed request details (method, URL, headers, body) for an AWS V4 signed request. ```javascript import { AwsV4Signer } from 'aws4fetch' const signer = new AwsV4Signer(opts) async function sign() { const { method, url, headers, body } = await signer.sign() console.log(method, url, [...headers], body) } ``` -------------------------------- ### JavaScript AWS Fetch Client Usage Example Source: https://github.com/mhart/aws4fetch Demonstrates how to use the `aws4fetch` library's `AwsClient` to perform authenticated AWS API requests, including various configuration options for the fetch call. ```javascript import { AwsClient } from 'aws4fetch' const aws = new AwsClient(opts) async function doFetch() { const response = await aws.fetch(url, { method, // if not supplied, will default to 'POST' if there's a body, otherwise 'GET' headers, // standard JS object literal, or Headers instance body, // optional, String or ArrayBuffer/ArrayBufferView – ie, remember to stringify your JSON // and any other standard fetch options, eg keepalive, etc // optional, largely if you want to override options in the AwsClient instance aws: { signQuery, // set to true to sign the query string instead of the Authorization header accessKeyId, // same as in AwsClient constructor above secretAccessKey, // same as in AwsClient constructor above sessionToken, // same as in AwsClient constructor above service, // same as in AwsClient constructor above region, // same as in AwsClient constructor above cache, // same as in AwsClient constructor above datetime, // defaults to now, to override use the form '20150830T123600Z' appendSessionToken, // set to true to add X-Amz-Security-Token after signing, defaults to true for iot allHeaders, // set to true to force all headers to be signed instead of the defaults singleEncode, // set to true to only encode %2F once (usually only needed for testing) }, }) console.log(await response.json()) } ``` -------------------------------- ### JavaScript Initialization for URL Parameter Tracking Source: https://www.anthropic.com/ The main initialization function that orchestrates the parameter tracking process. It retrieves current URL parameters and stores them if new ones are present. ```JavaScript // Initialize function function init() { log('Initializing...'); // Get tracking parameters from current URL const currentParams = utils.getTrackingParams(); // Store new parameters if present if (Object.keys(currentParams).length > 0) { utils.storeTrackingParams(currentParams); } } ``` -------------------------------- ### Example Deployed Cloudflare Worker URL Source: https://context7_llms An example URL format for a deployed Cloudflare Worker, showing how it's accessible via a `workers.dev` subdomain after deployment. ```text https://hello-ai..workers.dev ``` -------------------------------- ### Segment Analytics.js Integration and Initialization Source: https://www.anthropic.com/ This comprehensive snippet integrates Segment's analytics.js library into the website. It defines the analytics object, its methods, and handles loading the Segment script with a specific write key and API host for Anthropic. ```css .w-webflow-badge { display: none !important; } ``` ```javascript !function(){var i="analytics",analytics=window[i]=window[i]||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","screen","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware","register"];analytics.factory=function(e){return function(){if(window[i].initialized)return window[i][e].apply(window[i],arguments);var n=Array.prototype.slice.call(arguments);if(["track","screen","alias","group","page","identify"].indexOf(e)>-1){var c=document.querySelector("link[rel='canonical']");n.push({__t:"bpc",c:c&&c.getAttribute("href")||void 0,p:location.pathname,u:location.href,s:location.search,t:document.title,r:document.referrer})}n.unshift(e);analytics.push(n);return analytics}};for(var n=0;n { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }, // Get all tracking parameters from URL getTrackingParams: function() { const urlParams = new URLSearchParams(window.location.search); const params = {}; if (CONFIG.trackAllParams) { // Track all parameters except excluded ones for (const [key, value] of urlParams.entries()) { if (!CONFIG.excludeParams.includes(key.toLowerCase())) { params[key] = value; } } } else { // Track only specified parameters CONFIG.trackParams.forEach(param => { const value = urlParams.get(param); if (value) { params[param] = value; } }); } log('Extracted params:', params); return params; }, // Store parameters with expiration storeTrackingParams: function(params) { if (Object.keys(params).length > 0) { try { const data = { params: params, expiry: Date.now() + (CONFIG.sessionLength * 60 * 1000) }; sessionStorage.setItem(CONFIG.storageKey, JSON.stringify(data)); log('Stored params:', data); } catch (e) { log('Storage failed:', e); } } }, // Retrieve stored parameters getStoredTrackingParams: function() { try { const stored = sessionStorage.getItem(CONFIG.storageKey); if (!stored) return {}; const data = JSON.parse(stored); // Check if expired if (Date.now() > data.expiry) { sessionStorage.removeItem(CONFIG.storageKey); log('Parameters expired'); return {}; } log('Retrieved params:', data.params); return data.params || {}; } catch (e) { log('Retrieval failed:', e); return {}; } }, // Append parameters to URL appendParameters: function(url, params) { if (!url || typeof url !== 'string') return url; try { // Handle relative and absolute URLs const urlObj = new URL(url, window.location.origin); // Skip external domains (unless it's a subdomain) const currentHost = window.location.hostname; const urlHost = urlObj.hostname; if (urlHost !== currentHost && !urlHost.endsWith('.' + currentHost.split('.').slice(-2).join('.'))) { return url; } // Add parameters Object.keys(params).forEach(key => { if (!urlObj.searchParams.has(key)) { urlObj.searchParams.set(key, params[key]); } }); return urlObj.toString(); } catch (e) { // Fallback for malformed URLs if (url.indexOf('?') === -1) { const paramString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&'); return `${url}?${paramString}`; } return url; } }, // Check if URL should be excluded shouldExcludeURL: function(url) { return CONFIG.domainExcludePatterns.some(pattern => pattern.test(url)); } }; ``` -------------------------------- ### UI Component Styling with CSS Source: https://www.anthropic.com/ CSS rules defining styles for custom scrollbars, modal animations, and dynamic visibility based on CMS collection content. This snippet includes adjustments for Webkit and Firefox browsers, ensuring consistent UI behavior and appearance. ```css { background: rgba(250, 249, 240, 0.5); /* Brighter on hover - works in Chrome */ background-clip: content-box; /* Maintain the same behavior on hover */ } .terminal_content::-webkit-scrollbar-thumb:horizontal { border-top: 4px solid transparent; border-bottom: 6px solid transparent; /* Increased space from the bottom */ border-left: 4px solid transparent; border-right: 4px solid transparent; background-clip: content-box; } .terminal_content::-webkit-scrollbar-corner { background: transparent; /* For the corner where both scrollbars meet */ } /* Firefox */ .terminal_content { scrollbar-width: thin; scrollbar-color: rgba(250, 249, 240, 0.3) transparent; } /* Remove padding on Result tab */ .terminal_content.result-view { padding: 0px; } /*--- MODAL ---*/ /* Modal mods */ dialog.modal_wrap[open] { animation: fadein 400ms ease-out forwards; } dialog.modal_wrap::backdrop { background: color-mix(in srgb, var(--swatch--slate-dark) 80%, transparent); } @keyframes fadein{ 0%{ opacity:0; } 100%{ opacity:1; } } /*--- Hide element if child CMS collection is empty ---*/ [data-hide-if-empty-cms-child]:not(:has(.w-dyn-item)) { display: none; } /* In Designer only hacks html.wf-design-mode .g_clickable_wrap { pointer-events: none; } html.wf-design-mode a[href="#"], html.wf-design-mode a[href="#"] ~ button { outline: 3px solid red; } */ ``` -------------------------------- ### Execute Universal Request via AI Gateway Source: https://context7_llms This TypeScript example shows how to use the `run` method to execute a universal request through the AI Gateway, specifying the provider, endpoint, headers, and query parameters for the AI task. ```typescript const resp = await gateway.run({ provider: "workers-ai", endpoint: "@cf/meta/llama-3.1-8b-instruct", headers: { authorization: "Bearer my-api-token", }, query: { prompt: "tell me a joke", }, }); ``` -------------------------------- ### Initialize Cerebras Client and Start Chat Completion Source: https://inference-docs.cerebras.ai/ This Python snippet demonstrates how to initialize the Cerebras client using an API key retrieved from environment variables and how to begin a chat completion request. It utilizes the `cerebras.cloud.sdk` to interact with LLM services. ```python import os from cerebras.cloud.sdk import Cerebras client = Cerebras( api_key=os.environ.get("CEREBRAS_API_KEY"), ) chat_completion = client.chat.completions.create( ``` -------------------------------- ### Connect to AI Gateway via WebSockets Source: https://context7_llms This JavaScript example demonstrates how to establish a WebSocket connection to Cloudflare AI Gateway. It shows how to send a universal request to an LLM endpoint, specifying the provider, endpoint, and prompt, and how to listen for incoming messages from the gateway. ```javascript import WebSocket from "ws"; const ws = new WebSocket( "wss://gateway.ai.cloudflare.com/v1/my-account-id/my-gateway/", { headers: { "cf-aig-authorization": "Bearer AI_GATEWAY_TOKEN", }, }, ); ws.send( JSON.stringify({ type: "universal.create", request: { eventId: "my-request", provider: "workers-ai", endpoint: "@cf/meta/llama-3.1-8b-instruct", headers: { Authorization: "Bearer WORKERS_AI_TOKEN", "Content-Type": "application/json", }, query: { prompt: "tell me a joke", }, }, }), ); ws.on("message", function incoming(message) { console.log(message.toString()); }); ``` -------------------------------- ### Initialize Groq Client and Create Chat Completion Source: https://www.npmjs.com/package/groq-sdk Demonstrates how to initialize the Groq SDK client with an API key and make a chat completion request to an LLM model. It shows how to send a user message and log the response. ```TypeScript import Groq from 'groq-sdk'; const client = new Groq({ apiKey: process.env['GROQ_API_KEY'], // This is the default and can be omitted }); const chatCompletion = await client.chat.completions.create({ messages: [{ role: 'user', content: 'Explain the importance of low latency LLMs' }], model: 'llama3-8b-8192', }); console.log(chatCompletion[choices[0].message.content]); ``` -------------------------------- ### Get AI Gateway Base and Provider-Specific URLs Source: https://context7_llms This TypeScript example shows how to use `getUrl` to retrieve the base URL for an AI Gateway and also how to get a provider-specific URL, such as for OpenAI, enabling dynamic URL construction. ```typescript // Get the base gateway URL const baseUrl = await gateway.getUrl(); // Output: https://gateway.ai.cloudflare.com/v1/my-account-id/my-gateway/ // Get a provider-specific URL const openaiUrl = await gateway.getUrl("openai"); // Output: https://gateway.ai.cloudflare.com/v1/my-account-id/my-gateway/openai ``` -------------------------------- ### RocketPreloadLinks Class Initialization (Partial) Source: https://groq.com/ This partial JavaScript snippet defines the `RocketPreloadLinks` class, responsible for managing link preloading. It takes a browser compatibility checker instance and a configuration object. The `init` method checks for browser support and connection status before setting up regular expressions based on the provided configuration for excluding URIs and identifying image/file extensions. The full implementation would likely handle the actual prefetching logic, but the provided code is truncated. ```javascript (function() { "use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e=function(){function i(e,t){for(var n=0;n { const response = await env.AI.run( "@cf/meta/llama-3.1-8b-instruct", { prompt: "Why should you use Cloudflare for your AI inference?", }, { gateway: { id: "{gateway_id}", skipCache: false, cacheTtl: 3360, }, }, ); return new Response(JSON.stringify(response)); }, } satisfies ExportedHandler; ``` -------------------------------- ### Initialize Global JavaScript Context Object Source: https://www.npmjs.com/package/groq-sdk This JavaScript snippet defines the `window.__context__` global object, which holds application-wide settings, user information, and detailed package metadata for the `groq-sdk`. ```JavaScript window.__context__ = {"context":{"notifications":[],"csrftoken":"-r22q25kD3Dm3Wq8VA0mwraPD9DLPrNQPODJq7wLNtf","userEmailVerified":null,"auditLogEnabled":false,"user":null,"documentContext":{"readme.data":"readme"},"undefined":true,"readme":{"ref":"readme","data":null},"versionsDownloads":{"0.17.0":4520,"0.2.1":7,"0.15.0":10060,"0.7.0":7402,"0.4.0":1463,"0.5.0":162937,"0.6.1":3288,"0.14.0":1109,"0.3.0":6564,"0.22.0":2657,"0.21.0":1803,"0.3.3":21115,"0.3.2":1669,"0.9.1":4729,"0.24.0":1467,"0.10.0":12,"0.25.0":3403,"0.20.0":97,"0.18.0":232,"0.16.0":1064,"0.20.1":8684,"0.2.0":1,"0.23.0":5976,"0.12.0":2240,"0.9.0":294,"0.11.0":108,"0.19.0":19164,"0.13.0":2161,"0.8.0":10892,"0.3.1":9},"starAction":"/package/groq-sdk/star","provenance":{"enabled":false,"feedbackUrl":" https://github.com/npm/feedback"},"isSecurityPlaceholder":false,"private":false,"devDeps":[],"deps":["@types/node","@types/node-fetch","abort-controller","agentkeepalive","form-data-encoder","formdata-node","node-fetch"],"packument":{"author":{"name":"Groq","avatars":{"small":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci9kMGM1NmVjMmM3ZmI0YjVjNzBiYmUzNmNiM2FiYTQ3Mz9zaXplPTUwJmRlZmF1bHQ9cmV0cm8ifQ.y5ABbQNZnbfw91BK5DKaoFSAc8oLT8Nv1dCooy-ecGU","medium":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci9kMGM1NmVjMmM3ZmI0YjVjNzBiYmUzNmNiM2FiYTQ3Mz9zaXplPTEwMCZkZWZhdWx0PXJldHJvIn0.rfpajOwkxVNCIpTWVDldfUiK_CFJbc4T4QVd7YadTSI","large":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci9kMGM1NmVjMmM3ZmI0YjVjNzBiYmUzNmNiM2FiYTQ3Mz9zaXplPTQ5NiZkZWZhdWx0PXJldHJvIn0.r3Q9BWf88YWVYb_nsAutDBveiTkC2FygAS0aIBbcJAA"}},"description":"The official TypeScript library for the Groq API","homepage":"https://github.com/groq/groq-typescript#readme","repository":"https://github.com/groq/groq-typescript","distTags":{"latest":"0.25.0"},"maintainers":[{"name":"colemccracken","avatars":{"small":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8zMWI1MTRlZTMyNGRiZjg4NjU2ZThhNWQzMzVjZjI4MD9zaXplPTUwJmRlZmF1bHQ9cmV0cm8ifQ.a8PJcsSlss5ybW6b3C0ELMinQbNlmNKEGZ3yp6cwwns","medium":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8zMWI1MTRlZTMyNGRiZjg4NjU2ZThhNWQzMzVjZjI4MD9zaXplPTEwMCZkZWZhdWx0PXJldHJvIn0.N80XwFktzKgCqtHd7Q3L2UlBo8n9T6vO0JfPFJr03XA","large":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8zMWI1MTRlZTMyNGRiZjg4NjU2ZThhNWQzMzVjZjI4MD9zaXplPTQ5NiZkZWZhdWx0PXJldHJvIn0.0g8KBR4arw9ZW4PwA_tVhS03A9NOXGk7vBmMQXKbdko"}},{"name":"grea","avatars":{"small":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8xYTQwYWI1MDgwNjMyMTRmNTllYmUzZTNhOTRhMDQwOT9zaXplPTUwJmRlZmF1bHQ9cmV0cm8ifQ.1l2hfZEHT-6PZBY9DRfQCKtWOu-O6Wbg2UTVHImw33c","medium":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8xYTQwYWI1MDgwNjMyMTRmNTllYmUzZTNhOTRhMDQwOT9zaXplPTEwMCZkZWZhdWx0PXJldHJvIn0.lYYT5S1g4KrmOAtd8SnZG3p2HkoS3L2d0uOjiKZqDnw","large":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8xYTQwYWI1MDgwNjMyMTRmNTllYmUzZTNhOTRhMDQwOT9zaXplPTQ5NiZkZWZhdWx0PXJldHJvIn0.96THKZpV-a4qyAXuVu8N2c-zxzLiXwS2e9bi54nxpeY"}},{"name":"mtibben","avatars":{"small":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci80ZGIyZDQxMjIwNzFjOTA1NGIwZjAyODA1NGQwNDkzYT9zaXplPTUwJmRlZmF1bHQ9cmV0cm8ifQ.0c0hN5MnkZhfzgV60C1iMiYkwPv0wJhcWnT8wHRDM5I","medium":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci80ZGIyZDQxMjIwNzFjOTA1NGIwZjAyODA1NGQwNDkzYT9zaXplPTEwMCZkZWZhdWx0PXJldHJvIn0.fHz21YUCc9-TkTngMyL_rJsf1Eves9gHiHJgOPWzJj4","large":"/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci80ZGIyZDQxMjIwNzFjOTA1NGIwZjAyODA1NGQwNDkzYT9zaXplPTQ5NiZkZWZhdWx0PXJldHJvIn0.kvrfCaO8Y_gRqGdv6PXlk2IJ_icfFitHz0ycnEcVJ9A"}}],"name":"groq-sdk","license":"Apache-2.0","version":"0.25.0","versions":[{"version":"0.25.0","date":{"ts":1749744997828,"rel":"5 days ago"},"dist":{"shasum":"733c196f106e6bc262234c0521df3aaebe6c7504","tarball":"https://registry.npmjs.org/groq-sdk/-/groq-sdk-0.25.0.tgz","fileCount":307,"integrity":"sha512-IZQb/U0LZQcoF6Amoq8Kh+3seDYdk7278VrAOCz/W4I2nC7PvqEwik3RjRe3bxrOBFvUFHhL/3J+jzVzfjhZUQ==","signatures":[{"sig":"MEUCIEJdYlsesGVda/zZvO+iWYf+5MkS6ZAfRafaRxt5Y8Q1AiEA73S/FPlhHjt9jLonSFtq/zTsHql3ciVQ4CxHVKpSdYY=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}]}}]} ``` -------------------------------- ### AI Gateway Pricing and Log Storage Allocations Source: https://context7_llms Outlines the pricing structure for Cloudflare AI Gateway, including free core features, persistent log allocations for both free and paid plans, overage pricing for additional logs, and Logpush service costs. It clarifies that billing for persistent logs has not yet started and provides an example calculation for overage charges. ```APIDOC AI Gateway Core Features: Free (dashboard analytics, caching, rate limiting) Persistent Logs: Billing Status: Not yet started (users on paid plans can store beyond 200,000 logs without charge during this period; free plan remains limited to 100,000 logs cap). Free Allocation and Overage Pricing: Plan | Free logs stored | Overage pricing ------------ | ------------------ | ------------------------------------ Workers Free | 100,000 logs total | N/A - Upgrade to Workers Paid Workers Paid | 200,000 logs total | $8 per 100,000 logs stored per month Allocation Basis: Total logs stored across all gateways. Example: Workers Paid user storing 300,000 logs will be charged $8/month for the excess 100,000 logs. Logpush: Availability: Workers Paid plan only Pricing: Requests | 10 million / month, +$0.05/million ``` -------------------------------- ### Handle File Uploads for Audio Transcriptions with Groq SDK Source: https://www.npmjs.com/package/groq-sdk This section illustrates various methods for uploading files to the Groq SDK, specifically for audio transcription. It covers using Node.js `fs.createReadStream`, the Web `File` API, `fetch` `Response` objects, and the SDK's `toFile` helper for different data sources. Ensure necessary imports like `fs`, `fetch`, and `toFile` are present. ```TypeScript import fs from 'fs'; import Groq from 'groq-sdk'; const client = new Groq(); // If you have access to Node `fs` we recommend using `fs.createReadStream()`: await client.audio.transcriptions.create({ model: 'whisper-large-v3-turbo', file: fs.createReadStream('/path/to/file'), }); ``` ```TypeScript import Groq from 'groq-sdk'; const client = new Groq(); // Or if you have the web `File` API you can pass a `File` instance: await client.audio.transcriptions.create({ model: 'whisper-large-v3-turbo', file: new File(['my bytes'], 'file'), }); ``` ```TypeScript import fetch from 'node-fetch'; import Groq from 'groq-sdk'; const client = new Groq(); // You can also pass a `fetch` `Response`: await client.audio.transcriptions.create({ model: 'whisper-large-v3-turbo', file: await fetch('https://somesite/file'), }); ``` ```TypeScript import { toFile } from 'groq-sdk'; import Groq from 'groq-sdk'; const client = new Groq(); // Finally, if none of the above are convenient, you can use our `toFile` helper: await client.audio.transcriptions.create({ model: 'whisper-large-v3-turbo', file: await toFile(Buffer.from('my bytes'), 'file'), }); ``` ```TypeScript import { toFile } from 'groq-sdk'; import Groq from 'groq-sdk'; const client = new Groq(); await client.audio.transcriptions.create({ model: 'whisper-large-v3-turbo', file: await toFile(new Uint8Array([0, 1, 2]), 'file'), }); ``` -------------------------------- ### Manage User Cookie Consent Preferences Source: https://www.anthropic.com/ This JavaScript module handles user consent preferences, storing them in a cookie. It determines if explicit consent is required based on the user's country (derived from navigator language) and integrates with Google Tag Manager (GTM) to update consent states for analytics and marketing purposes. It defines cookie utility functions for getting, setting, and checking cookie presence. ```javascript (function() { 'use strict'; // Constants const CONSENT_PREFERENCES_COOKIE_KEY = 'anthropic-consent-preferences'; const EXPLICIT_CONSENT_COUNTRIES = new Set([ 'CA', 'UK', 'BE', 'EL', 'LT', 'PT', 'BG', 'ES', 'LU', 'RO', 'CZ', 'FR', 'RE', 'GP', 'MQ', 'GF', 'YT', 'BL', 'MF', 'PM', 'WF', 'PF', 'NC', 'HU', 'SI', 'DK', 'FO', 'GL', 'HR', 'MT', 'SK', 'DE', 'IT', 'NL', 'AW', 'CW', 'SX', 'FI', 'AX', 'EE', 'CY', 'AT', 'SE', 'IE', 'LV', 'PL', 'GB', 'AI', 'BM', 'IO', 'VG', 'KY', 'FK', 'GI', 'MS', 'PN', 'SH', 'TC', 'GG', 'JE', 'IM', 'BR', 'IN' ]); // Cookie utilities (optimized) const cookieUtils = { get(name) { const match = document.cookie.match(new RegExp('(^| )' + name + '=(.+?)')); return match ? decodeURIComponent(match[2]) : undefined; }, set(name, value, options = {}) { const cookieParts = [ `${name}=${encodeURIComponent(value)}`, `max-age=${60 * 60 * 24 * 365}`, 'path=/', 'samesite=lax', 'secure' ]; if (options.domain) cookieParts.push(`domain=${options.domain}`); document.cookie = cookieParts.join('; '); }, has(name) { return document.cookie.indexOf(`${name}=`) !== -1; } }; // Consent logic (optimized) function inExplicitConsentRequiredCountry() { try { const lang = navigator.languages?.[0] || navigator.language; return EXPLICIT_CONSENT_COUNTRIES.has(lang.split('-')[1]); } catch (e) { return false; } } function getInitialConsentPreferences() { const consentPreferencesCookie = cookieUtils.get(CONSENT_PREFERENCES_COOKIE_KEY); if (consentPreferencesCookie) { try { return JSON.parse(consentPreferencesCookie); } catch { // Fallback to default } } const isExplicitRequired = inExplicitConsentRequiredCountry(); return { analytics: !isExplicitRequired, marketing: !isExplicitRequired }; } function updateGTMConsentPreferences(preferences) { if (typeof window.gtag !== 'function') return; window.gtag('consent', 'update', { 'ad_personalization': preferences.marketing ? 'granted' : 'denied', 'ad_user_data': preferences.marketing ? 'granted' : 'denied', 'ad_storage': preferences.marketing ? 'granted' : 'denied', 'analytics_storage': preferences.analytics ? 'granted' : 'denied', 'functionality_storage': 'granted', 'personalization_storage': 'granted', 'security_storage': 'granted' }); } function saveConsentPreferences(preferences) { cookieUtils.set( CONSENT_PREFERENCES_COOKIE_ ``` -------------------------------- ### JavaScript Website Initialization and Stripe Integration Source: https://huggingface.co/ This JavaScript snippet handles initial script imports, sets a global `moonSha` variable, initializes a deferred object, and conditionally loads the Stripe V3 SDK if the hostname is 'hf.co' or 'huggingface.co'. It's crucial for core site functionality and payment processing integration. ```JavaScript import("\/front\/build\/kube-c9cbb38\/index.js"); window.moonSha = "kube-c9cbb38\/"; window.__hf_deferred = {}; if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } ``` -------------------------------- ### Install Cohere Python Client Source: https://github.com/cohere-ai/cohere-python Install the Cohere Python client library using pip, which is required to interact with Cohere models and the Cloudflare AI Gateway. ```Shell pip install cohere ``` -------------------------------- ### Run a Pre-trained Model on Replicate (Python) Source: https://replicate.com/ This snippet demonstrates how to run a pre-trained model available on Replicate using the Python client library. It shows how to specify the model identifier and input parameters, then print the output. ```Python import replicate output = replicate.run( "black-forest-labs/flux-dev", input={ "aspect_ratio": "1:1", "num_outputs": 1, "output_format": "jpg", "output_quality": 80, "prompt": "An astronaut riding a rainbow unicorn, cinematic, dramatic", } ) print(output) ``` -------------------------------- ### Grok Model JSON Configuration Example Source: https://context7_llms Provides an example of the JSON structure used to specify the Grok model within a request payload for the Cloudflare AI Gateway. ```json { "model": "grok/{model}" } ``` -------------------------------- ### Create Chat Completion with Groq SDK Source: https://www.npmjs.com/package/groq-sdk This snippet demonstrates how to initialize the Groq SDK client and create a chat completion request. It shows how to define messages with roles and content, specify the model, and handle the asynchronous API call to get a chat completion response. ```TypeScript import Groq from 'groq-sdk'; const client = new Groq({ apiKey: process.env['GROQ_API_KEY'], // This is the default and can be omitted }); const params: Groq.Chat.CompletionCreateParams = { messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Explain the importance of low latency LLMs' }, ], model: 'llama3-8b-8192', }; const chatCompletion: Groq.Chat.ChatCompletion = await client.chat.completions.create(params); ```