利用Cloudflare AI打造智能网站助手

一、前期准备

1. 注册Cloudflare账户:

  1. 访问https://cloudflare.com官网并注册一个账户。
  2. 验证邮箱并登录账户。

2. 添加网站到Cloudflare:

  1. 在Cloudflare dashboard中添加你的网站域名。
  2. 更新域名的DNS设置,将DNS服务器指向Cloudflare的DNS。

3. 获取认证信息:

  1. 从AI dashboard页面获取必要的认证信息,包括Account ID和API Token。

二、集成Cloudflare AI服务

1. 了解Cloudflare AI支持的模型:

  1. Cloudflare AI目前免费支持多种模型,如@cf/meta/llama-2-7b-chat-int8、@cf/openai/whisper等。
  2. 参考API文档,了解各模型的功能和使用方法。

2. 测试AI模型:

使用以下命令行示例,结合获取的`ACCOUNT_ID`和`API_TOKEN`,快速测试这些模型:

   curl -X POST \  https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/run/@cf/meta/llama-2-7b-chat-int8 \

     -H "Authorization: Bearer {API_TOKEN}" \

     -d '{"messages":[{"role":"system","content":"You are a friendly assistant"},{"role":"user","content":"Why is pizza so good"}]}'

三、编写和部署Cloudflare Worker

1. 处理CORS问题:

由于使用Cloudflare Page时可能会遇到跨源资源共享(CORS)问题,通过Cloudflare Worker构建服务来解决这个问题。

编写以下基本的Cloudflare Worker脚本,用于处理CORS和转发AI模型请求:

  addEventListener('fetch', event => {

     event.respondWith(handleRequest(event.request))

   })

   // 主要的请求处理函数

   async function handleRequest(request) {

     // 处理 CORS 预检请求

     if (request.method === "OPTIONS") {

       return handleCors();

     }

     return handleChatGPTRequest(request);

   }

   // 处理 CORS 预检请求的函数

   function handleCors() {

     return new Response(null, {

       headers: {

         "Access-Control-Allow-Origin": "*",

         "Access-Control-Allow-Methods": "POST, OPTIONS"

       }

     });

   }

   async function handleChatGPTRequest(request) {

     const url = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/ai/run/@cf/meta/llama-2-7b-chat-int8`;

     const headers = {

       "Authorization": `Bearer ${BEARER_TOKEN}`,

       "Content-Type": "application/json"

     };

     const newRequest = new Request(url, {

       method: "POST",

       headers: headers,

       body: request.body

     });

     const response = await fetch(newRequest);

     const newResponse = new Response(response.body, response);

     newResponse.headers.set("Access-Control-Allow-Origin", "*");

     return newResponse;

   }

2. 部署Workers脚本:

  1. 将此脚本上传到Cloudflare Worker。
  2. 在Worker设置中(Settings -> Variables),配置ACCOUNT_ID和BEARER_TOKEN。
  3. 测试Worker:点击Quick Edit,直接利用Cloudflare的内置功能进行测试。

四、构建前端界面 with Cloudflare Pages

1. 设计AI应用界面:

  • 使用Cloudflare Page作为前端,负责页面构建和用户交互。
  • 根据个人审美设计AI应用界面,并且可以将其与GitHub项目直接关联。

2. 前端HTML代码:

下面是一个简单的前端HTML代码,用于与AI助手进行交互:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>AI Assistant</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            margin: 0;

            padding: 0;

            display: flex;

            justify-content: center;

            align-items: center;

            height: 100vh;

            flex-direction: column;

        }

        textarea {

            width: 80%;

            height: 100px;

            margin-bottom: 10px;

        }

        button {

            padding: 10px 20px;

            font-size: 16px;

            cursor: pointer;

        }

        #response {

            margin-top: 20px;

            width: 80%;

            border: 1px solid #ddd;

            padding: 10px;

            white-space: pre-wrap;

        }

    </style>

</head>

<body>

    <h1>AI Assistant</h1>

    <div>

        <textarea id="userInput" placeholder="Type your message here..."></textarea>

    </div>

    <button onclick="sendMessage()">Send</button>

    <div id="response"></div>

    <script>

        async function sendMessage() {

            const userInput = document.getElementById('userInput').value;

            const responseElement = document.getElementById('response');

            // 构造请求数据

            const data = {

                messages: [

                    { role: "user", content: userInput }

                ]

            };

            // 发送请求到Cloudflare Worker

            const response = await fetch('https://your-worker-subdomain.cloudflareworkers.com', {

                method: 'POST',

                headers: {

                    'Content-Type': 'application/json'

                },

                body: JSON.stringify(data)

            });

            // 处理响应

            if (response.ok) {

                const result = await response.json();

                responseElement.textContent = result.responses[0].text;

            } else {

                responseElement.textContent = 'Error: ' + response.statusText;

            }

        }

    </script>

</body>

</html>

五、部署和测试

1. 部署前端页面:

  1. 将上述HTML代码保存为文件,并通过Cloudflare Pages部署。
  2. 确保你的Cloudflare Pages项目与GitHub仓库关联,以便自动部署。

2. 测试整个流程:

  1. 访问部署后的前端页面。
  2. 输入消息并点击发送,查看AI助手的响应。

六、后续优化

1. 优化用户体验:

  • 根据用户反馈优化界面设计和交互逻辑。
  • 添加加载指示器,改善等待响应时的用户体验。

2. 监控和日志:

  • 利用Cloudflare的监控和日志功能,跟踪API调用和用户行为。
  • 根据日志数据优化API使用和性能。

3. 安全考虑:

  • 确保所有通信都通过HTTPS进行。
  • 对输入数据进行验证,防止注入攻击。

七、结语

通过以上步骤,你就可以利用Cloudflare AI搭建一个能够搜索网络资源的网站AI助手了。随着人工智能技术的不断进步,我们有理由相信,未来的网站将更加智能、高效和人性化。

posted @ 2025-01-28 10:54  IMwy  阅读(79)  评论(0)    收藏  举报  来源