以下是在 Vue3 项目中零成本接入 AI 能力(以图搜图、知识问答、文本匹配)的完整解决方案,结合免费 API 和开源工具实现,无需服务器或付费服务:
一、以图搜图(基于 Hugging Face CLIP 模型)
核心思路
通过 Hugging Face Inference API 调用 CLIP 模型,将图片转换为向量后进行相似度检索。
免费额度:每月 30k 次 API 调用(足够小规模使用)。
实现步骤
- 注册 Hugging Face 账号,获取 API Token(免费)。
- 安装依赖:
npm install axios
- 封装图片搜索函数:
// 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; // 返回图像特征向量 }
- 在 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