Perplexica API开发指南:构建自定义搜索应用

Perplexica API开发指南:构建自定义搜索应用

【免费下载链接】Perplexica Perplexica is an AI-powered search engine. It is an Open source alternative to Perplexity AI 【免费下载链接】Perplexica 项目地址: https://gitcode.com/GitHub_Trending/pe/Perplexica

概述

Perplexica是一个开源的AI驱动搜索引擎,提供了强大的API接口,允许开发者将其智能搜索能力集成到自定义应用中。本指南将详细介绍如何使用Perplexica API构建功能丰富的搜索应用,涵盖API端点、请求参数、响应格式以及最佳实践。

API基础架构

Perplexica基于Next.js构建,采用模块化架构设计,支持多种搜索模式和AI模型提供商。其API架构遵循RESTful设计原则,提供标准化的JSON请求和响应格式。

核心API端点

端点方法描述认证要求
/api/searchPOST执行AI驱动的搜索查询可选API密钥
/api/modelsGET获取可用模型列表
/api/chatPOST聊天对话接口可选API密钥
/api/configGET获取配置信息

搜索API详解

基本请求格式

const searchRequest = {
  chatModel: {
    provider: "openai",
    name: "gpt-4o-mini"
  },
  embeddingModel: {
    provider: "openai", 
    name: "text-embedding-3-large"
  },
  optimizationMode: "balanced",
  focusMode: "webSearch",
  query: "什么是人工智能的最新发展",
  history: [
    ["human", "你好,我想了解AI技术"],
    ["assistant", "很高兴为您介绍人工智能技术"]
  ],
  systemInstructions: "请提供技术细节和实际应用案例",
  stream: false
};

焦点模式(Focus Modes)

Perplexica支持6种专业的搜索焦点模式,每种模式针对特定场景优化:

mermaid

模型配置选项

聊天模型提供商
  • OpenAI: GPT系列模型(gpt-4o, gpt-4o-mini等)
  • Ollama: 本地LLM部署(Llama, Mistral, Qwen等)
  • Anthropic: Claude系列模型
  • Groq: 高速推理模型
  • Gemini: Google AI模型
  • DeepSeek: 深度求索模型
  • 自定义OpenAI: 自部署模型服务
嵌入模型提供商
  • OpenAI: text-embedding-3系列
  • 本地嵌入模型: 支持各种开源嵌入模型

实战示例

示例1:基础搜索请求

// 使用Fetch API调用Perplexica搜索
async function performSearch(query, focusMode = 'webSearch') {
  const response = await fetch('http://localhost:3000/api/search', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      focusMode: focusMode,
      query: query,
      optimizationMode: 'balanced',
      stream: false
    })
  });

  if (!response.ok) {
    throw new Error(`搜索请求失败: ${response.status}`);
  }

  return await response.json();
}

// 使用示例
const result = await performSearch('机器学习的最新进展', 'academicSearch');
console.log(result.message);
console.log('来源:', result.sources.map(s => s.metadata.title));

示例2:流式响应处理

// 处理流式响应
async function streamSearch(query, onData, onComplete) {
  const response = await fetch('http://localhost:3000/api/search', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      focusMode: 'webSearch',
      query: query,
      stream: true
    })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  
  try {
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split('\n').filter(line => line.trim());
      
      for (const line of lines) {
        try {
          const data = JSON.parse(line);
          onData(data);
        } catch (e) {
          console.warn('解析JSON失败:', e);
        }
      }
    }
  } finally {
    reader.releaseLock();
    onComplete();
  }
}

// 使用流式搜索
streamSearch(
  '人工智能伦理问题',
  (data) => {
    switch (data.type) {
      case 'response':
        process.stdout.write(data.data);
        break;
      case 'sources':
        console.log('\n\n来源:', data.data.map(s => s.metadata.title));
        break;
    }
  },
  () => console.log('\n搜索完成')
);

示例3:多轮对话上下文

class PerplexicaChat {
  constructor() {
    this.history = [];
  }

  async sendMessage(message, focusMode = 'webSearch') {
    // 添加用户消息到历史
    this.history.push(['human', message]);

    const response = await fetch('http://localhost:3000/api/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        focusMode: focusMode,
        query: message,
        history: this.history,
        optimizationMode: 'balanced',
        stream: false
      })
    });

    const result = await response.json();
    
    // 添加助手回复到历史
    this.history.push(['assistant', result.message]);
    
    return {
      message: result.message,
      sources: result.sources,
      history: this.history
    };
  }

  clearHistory() {
    this.history = [];
  }
}

// 使用聊天类
const chat = new PerplexicaChat();

// 第一轮对话
const response1 = await chat.sendMessage('什么是Transformer模型?', 'academicSearch');
console.log('回答:', response1.message);

// 第二轮对话(保持上下文)
const response2 = await chat.sendMessage('它在NLP中有什么应用?');
console.log('后续回答:', response2.message);

高级功能配置

自定义模型配置

// 使用自定义OpenAI兼容端点
const customConfig = {
  chatModel: {
    provider: "custom_openai",
    name: "my-local-model",
    customOpenAIBaseURL: "http://localhost:8080/v1",
    customOpenAIKey: "your-api-key-here"
  },
  embeddingModel: {
    provider: "openai",
    name: "text-embedding-3-small"
  },
  focusMode: "webSearch",
  query: "自定义模型测试查询",
  stream: false
};

系统指令定制

// 专业领域定制指令
const professionalInstructions = {
  systemInstructions: `你是一个资深技术专家,请遵循以下要求:
  1. 提供详细的技术实现细节
  2. 包含代码示例和最佳实践
  3. 引用权威的技术文档和标准
  4. 分析不同方案的优缺点
  5. 提供实际应用场景案例`
};

// 创意写作指令  
const creativeInstructions = {
  systemInstructions: `你是一个创意写手,请:
  1. 使用生动形象的语言描述
  2. 包含比喻和修辞手法
  3. 保持文章的可读性和趣味性
  4. 适当使用排比和对比
  5. 确保内容积极向上`
};

错误处理与重试机制

健壮的API客户端实现

class PerplexicaClient {
  constructor(baseURL = 'http://localhost:3000', maxRetries = 3) {
    this.baseURL = baseURL;
    this.maxRetries = maxRetries;
  }

  async request(endpoint, options, retryCount = 0) {
    try {
      const response = await fetch(`${this.baseURL}${endpoint}`, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...options.headers,
        },
      });

      if (!response.ok) {
        if (response.status >= 500 && retryCount < this.maxRetries) {
          // 服务器错误,重试
          await this.delay(1000 * (retryCount + 1));
          return this.request(endpoint, options, retryCount + 1);
        }
        throw new Error(`HTTP ${response.status}: ${await response.text()}`);
      }

      return await response.json();
    } catch (error) {
      if (retryCount < this.maxRetries) {
        await this.delay(1000 * (retryCount + 1));
        return this.request(endpoint, options, retryCount + 1);
      }
      throw error;
    }
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  async search(params) {
    return this.request('/api/search', {
      method: 'POST',
      body: JSON.stringify(params),
    });
  }

  async getModels() {
    return this.request('/api/models', { method: 'GET' });
  }
}

// 使用健壮客户端
const client = new PerplexicaClient();
try {
  const models = await client.getModels();
  console.log('可用模型:', models);
  
  const result = await client.search({
    focusMode: 'webSearch',
    query: 'API开发最佳实践',
    optimizationMode: 'balanced'
  });
  
  console.log('搜索结果:', result);
} catch (error) {
  console.error('API调用失败:', error.message);
}

性能优化策略

缓存机制实现

class CachedSearchService {
  constructor(ttl = 5 * 60 * 1000) { // 5分钟缓存
    this.cache = new Map();
    this.ttl = ttl;
  }

  getCacheKey(params) {
    return JSON.stringify({
      query: params.query,
      focusMode: params.focusMode,
      chatModel: params.chatModel,
      embeddingModel: params.embeddingModel
    });
  }

  async search(params) {
    const cacheKey = this.getCacheKey(params);
    const cached = this.cache.get(cacheKey);

    if (cached && Date.now() - cached.timestamp < this.ttl) {
      return cached.data;
    }

    const result = await fetch('http://localhost:3000/api/search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(params)
    }).then(r => r.json());

    this.cache.set(cacheKey, {
      data: result,
      timestamp: Date.now()
    });

    return result;
  }

  clearCache() {
    this.cache.clear();
  }
}

批量请求处理

async function batchSearch(queries, focusMode = 'webSearch') {
  const results = [];
  
  for (const query of queries) {
    try {
      const result = await fetch('http://localhost:3000/api/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          focusMode,
          query,
          optimizationMode: 'speed' // 批量处理使用速度模式
        })
      });
      
      results.push(await result.json());
    } catch (error) {
      results.push({ error: error.message, query });
    }
    
    // 添加延迟避免速率限制
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  return results;
}

应用场景案例

案例1:智能客服系统

class AICustomerService {
  constructor() {
    this.sessionContexts = new Map();
  }

  async handleCustomerQuery(sessionId, query, productContext) {
    const context = this.sessionContexts.get(sessionId) || [];
    
    const systemInstructions = `你是${productContext.productName}的客服专家。
产品特点: ${productContext.features}
常见问题: ${productContext.faqs}
请以专业、友好的态度回答客户问题。`;

    const response = await fetch('http://localhost:3000/api/search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        focusMode: 'webSearch',
        query: query,
        history: context,
        systemInstructions: systemInstructions,
        optimizationMode: 'balanced'
      })
    });

    const result = await response.json();
    
    // 更新会话上下文
    context.push(['human', query]);
    context.push(['assistant', result.message]);
    this.sessionContexts.set(sessionId, context);
    
    return {
      answer: result.message,
      sources: result.sources,
      suggestedActions: this.extractActions(result.message)
    };
  }

  extractActions(message) {
    // 从回复中提取建议操作
    const actions = [];
    if (message.includes('重置') || message.includes('reset')) {
      actions.push('指导重置操作');
    }
    if (message.includes('联系') || message.includes('contact')) {
      actions.push('提供联系方式');
    }
    return actions;
  }
}

案例2:学术研究助手

【免费下载链接】Perplexica Perplexica is an AI-powered search engine. It is an Open source alternative to Perplexity AI 【免费下载链接】Perplexica 项目地址: https://gitcode.com/GitHub_Trending/pe/Perplexica

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值