Vue3 项目中零成本接入 AI 能力(以图搜图、知识问答、文本匹配...

2 阅读3分钟

以下是在 Vue3 项目中零成本接入 AI 能力(以图搜图、知识问答、文本匹配)的完整解决方案,结合免费 API 和开源工具实现,无需服务器或付费服务:

一、以图搜图(基于 Hugging Face CLIP 模型)

核心思路

通过 Hugging Face Inference API 调用 CLIP 模型,将图片转换为向量后进行相似度检索。
免费额度:每月 30k 次 API 调用(足够小规模使用)。

实现步骤

  1. 注册 Hugging Face 账号,获取 API Token(免费)。
  2. 安装依赖
    npm install axios
    
  3. 封装图片搜索函数
    // services/imageSearch.ts
    import axios from 'axios';
    
    const API_URL = 'https://api-inference.huggingface.co/models/openai/clip-vit-base-patch32';
    const API_TOKEN = 'YOUR_HUGGING_FACE_TOKEN';
    
    export async function searchSimilarImages(imageUrl: string) {
      const response = await axios.post(
        API_URL,
        {
          inputs: imageUrl, // 支持 URL 或 base64 格式
          options: { wait_for_model: true }
        },
        {
          headers: {
            Authorization: `Bearer ${API_TOKEN}`,
            'Content-Type': 'application/json'
          }
        }
      );
      return response.data; // 返回图像特征向量
    }
    
  4. 在 Vue 组件中使用
    <template>
      <div>
        <input type="file" @change="handleImageUpload" />
        <button @click="search">搜索相似图片</button>
      </div>
    </template>
    
    <script setup>
    import { searchSimilarImages } from '@/services/imageSearch';
    
    const handleImageUpload = async (e: Event) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;
    
      const imageUrl = URL.createObjectURL(file);
      const features = await searchSimilarImages(imageUrl);
      // 此处需将特征向量与现有图库对比(需自建向量数据库)
    };
    </script>
    

关键说明

  • 自建向量数据库:CLIP 仅生成特征向量,需结合开源向量数据库(如 Chroma)存储图片特征,实现检索。示例代码:
    import { ChromaClient } from 'chromadb';
    
    const client = new ChromaClient();
    const collection = client.getOrCreateCollection('image-features');
    
    // 插入特征向量
    await collection.add({
      ids: ['image-1'],
      embeddings: [features]
    });
    
    // 搜索相似图片
    const results = await collection.query({
      query_embeddings: [features],
      n_results: 5
    });
    

二、知识问答(基于 Hugging Face 开源模型)

核心思路

使用 Hugging Face Inference API 调用轻量级问答模型(如 google/flan-t5-small),实现零成本问答。
免费额度:每月 30k 次 API 调用。

实现步骤

  1. 封装问答函数
    // services/questionAnswering.ts
    import axios from 'axios';
    
    const API_URL = 'https://api-inference.huggingface.co/models/google/flan-t5-small';
    const API_TOKEN = 'YOUR_HUGGING_FACE_TOKEN';
    
    export async function askQuestion(question: string) {
      const response = await axios.post(
        API_URL,
        {
          inputs: `question: ${question} context: 中国的首都是北京`,
          options: { wait_for_model: true }
        },
        {
          headers: {
            Authorization: `Bearer ${API_TOKEN}`,
            'Content-Type': 'application/json'
          }
        }
      );
      return response.data[0].generated_text; // 返回答案
    }
    
  2. 在 Vue 组件中使用
    <template>
      <div>
        <input v-model="question" placeholder="输入问题" />
        <button @click="answer">获取答案</button>
        <p>{{ answerText }}</p>
      </div>
    </template>
    
    <script setup>
    import { askQuestion } from '@/services/questionAnswering';
    import { ref } from 'vue';
    
    const question = ref('');
    const answerText = ref('');
    
    const answer = async () => {
      answerText.value = await askQuestion(question.value);
    };
    </script>
    

三、文本匹配(基于 Sentence Transformers)

核心思路

使用 Hugging Face Inference API 调用 sentence-transformers/all-MiniLM-L6-v2 模型,计算文本相似度。
免费额度:每月 30k 次 API 调用。

实现步骤

  1. 封装文本匹配函数
    // services/textMatching.ts
    import axios from 'axios';
    
    const API_URL = 'https://api-inference.huggingface.co/models/sentence-transformers/all-MiniLM-L6-v2';
    const API_TOKEN = 'YOUR_HUGGING_FACE_TOKEN';
    
    export async function compareTexts(text1: string, text2: string) {
      const response = await axios.post(
        API_URL,
        {
          inputs: [text1, text2],
          options: { wait_for_model: true }
        },
        {
          headers: {
            Authorization: `Bearer ${API_TOKEN}`,
            'Content-Type': 'application/json'
          }
        }
      );
      const embeddings = response.data;
      // 计算余弦相似度
      const similarity = cosineSimilarity(embeddings[0], embeddings[1]);
      return similarity;
    }
    
    function cosineSimilarity(a: number[], b: number[]): number {
      const dotProduct = a.reduce((acc, val, i) => acc + val * b[i], 0);
      const normA = Math.sqrt(a.reduce((acc, val) => acc + val ** 2, 0));
      const normB = Math.sqrt(b.reduce((acc, val) => acc + val ** 2, 0));
      return dotProduct / (normA * normB);
    }
    
  2. 在 Vue 组件中使用
    <template>
      <div>
        <textarea v-model="textA" placeholder="文本A"></textarea>
        <textarea v-model="textB" placeholder="文本B"></textarea>
        <button @click="match">计算相似度</button>
        <p>相似度:{{ similarity }}</p>
      </div>
    </template>
    
    <script setup>
    import { compareTexts } from '@/services/textMatching';
    import { ref } from 'vue';
    
    const textA = ref('');
    const textB = ref('');
    const similarity = ref(0);
    
    const match = async () => {
      similarity.value = await compareTexts(textA.value, textB.value);
    };
    </script>
    

四、零成本方案总结

功能实现方式成本
以图搜图Hugging Face CLIP + Chroma(自建向量数据库)免费(Hugging Face 30k 次/月)
知识问答Hugging Face google/flan-t5-small免费(Hugging Face 30k 次/月)
文本匹配Hugging Face sentence-transformers/all-MiniLM-L6-v2免费(Hugging Face 30k 次/月)

五、注意事项

  1. API 调用限制

    • Hugging Face 免费层限制为 30k 次/月,超出后需付费。
    • 建议在开发阶段使用免费额度,生产环境考虑付费方案或自建模型。
  2. 图片处理

    • 上传图片需转换为 base64 格式或提供 公开 URL
    • 示例代码(转换为 base64):
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;
      
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const base64Image = reader.result as string;
        // 调用 API 时使用 base64Image
      };
      
  3. 性能优化

    • 使用 防抖函数 减少高频 API 调用。
    • 前端缓存常用结果,避免重复请求。
  4. CORS 问题

    • Hugging Face Inference API 支持跨域,无需额外配置。
    • 若遇到 CORS 错误,可尝试添加 headers: { 'Access-Control-Allow-Origin': '*' }

六、扩展方案

  1. 自建模型部署

    • 使用 Hugging Face Spaces 免费托管模型(需绑定信用卡,但基础服务免费)。
    • 示例代码(部署 CLIP 模型):
      git clone https://huggingface.co/spaces/openai/clip-vit-base-patch32
      cd clip-vit-base-patch32
      pip install -r requirements.txt
      huggingface-cli login
      huggingface-cli space deploy
      
  2. 腾讯云/阿里云免费资源

    • 腾讯云 TI-ONE 平台 提供免费 GPU 算力(需申请)。
    • 阿里云 机器学习平台 PAI 提供免费实验资源。

通过以上方案,可在 零成本 下快速为 Vue3 项目集成 AI 能力,满足以图搜图、知识问答和文本匹配需求。实际应用中需根据业务场景优化模型选择和 API 调用策略。