首页 > 其他分享 >ChatGPT联网查询基于yahoo搜索引擎

ChatGPT联网查询基于yahoo搜索引擎

时间:2023-08-13 09:35:31浏览次数:36  
标签:zh return yahoo replace instructionMessage new const ChatGPT 搜索引擎

联网查询原理很简单1.对搜索内容分词 2.将分词后的内容用yahoo搜索 3.将搜索返回的内容交给ChatGPT整理提炼

Demo代码如下

import fetch from 'node-fetch';
import Segment from 'segment';
import { HttpsProxyAgent } from 'https-proxy-agent';


const proxyUrl = 'http://127.0.0.1:9981';
const agent = new HttpsProxyAgent(proxyUrl);

const segment = new Segment();
segment.useDefault();

function sendPostLw(requestUrl) {
    const headers = {
        'Host': 'sg.search.yahoo.com',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    };

    return fetch(requestUrl, { agent, headers })
        .then(response => {
            if (!response.ok) {
                throw new Error('访问出错');
            }

            return response.text();
        });
}

function calculateCost(numTokens) {
    const costPerToken = 0.000003;
    const totalCost = numTokens * costPerToken;
    return totalCost;
}

function calculateCosts(numTokens) {
    const costPerToken = 0.000004;
    const totalCost = numTokens * costPerToken;
    return totalCost;
}

function sendPostJson(jsonStr, key) {
    const timeout = 120;
    const headers = {
        'Host': 'api.openai.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Bearer ${key}`,
    };

    return fetch('https://api.openai.com/v1/chat/completions', {
        agent,
        method: 'POST',
        headers,
        body: jsonStr,
        timeout,
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('访问出错');
            }

            return response.json();
        });
}

function getCurrentDate() {
    const currentTimestamp = Date.now();
    const date = new Date(currentTimestamp);
    const formattedTime = date.toISOString().replace(/\.\d+Z$/, '').replace('T', ' ');
    return formattedTime;
}

async function processInstructions(instructionMessage, key) {
    const segList = segment.doSegment(instructionMessage, {
        simple: true
    });
    const segListResult = segList.join(' ');
    const messageEncode = encodeURIComponent(segListResult);
    const sendUrl = `https://sg.search.yahoo.com/search?p=${messageEncode}&ei=UTF-8`;
    const requestData = await sendPostLw(sendUrl);

    const titleMatches = requestData.match(/aria-label="(.*?)"/g);
    const contentMatches = requestData.match(/<span class=" fc-falcon">(.*?)<\/span>/g);
    const urlMatches = requestData.match(/class="d-ib p-abs t-0 l-0 fz-14 lh-20 fc-obsidian wr-bw ls-n pb-4"><span>(.*?)<\/span><span>/g);

    if (!titleMatches || !contentMatches || !urlMatches) {
        throw new Error('获取问答失败');
    }

    const searchUrls = urlMatches.map(url => url.replace(/class="d-ib p-abs t-0 l-0 fz-14 lh-20 fc-obsidian wr-bw ls-n pb-4"><span>/, '').replace(/<\/span><span>/, ''));
    const searchTitles = titleMatches.map(title => title.replace(/aria-label="/, '').replace(/"/, ''));
    const searchContents = contentMatches.map(content => content.replace(/<span class=" fc-falcon">/, '').replace(/<\/span>/, ''));

    const aggregateArray = [];
    for (let i = 0; i < 3; i++) {
        const index = i + 1;
        const singleContent = searchContents[i];
        const singleTitle = searchTitles[i];
        const singleUrl = searchUrls[i];
        const singleContentCleaned = singleContent.replace(/<.*?>/g, '');
        const singleString = `NUMBER:${index}\nURL:${singleUrl}\nTITLE:${singleTitle}\nCONTENT:${singleContent}`;
        aggregateArray.push(singleString);
    }

    const compiledContents = aggregateArray.join('\n\n');
    const currentDate = getCurrentDate();
    const replyInstruction = `I will give you a question or an instruction. Your objective is to answer my question or fulfill my instruction.\n\nMy question or instruction is: ${instructionMessage}\n\nFor your reference, today's date is ${currentDate}.\n\nIt's possible that the question or instruction, or just a portion of it, requires relevant information from the internet to give a satisfactory answer or complete the task. Therefore, provided below is the necessary information obtained from the internet, which sets the context for addressing the question or fulfilling the instruction. You will write a comprehensive reply to the given question or instruction. Do not include urls and sources in the summary text. If the provided information from the internet results refers to multiple subjects with the same name, write separate answers for each subject:\n\"\"\"\n${compiledContents}\n\"\"\"\nReply in 中文`;

    const postData = JSON.stringify({
        model: 'gpt-3.5-turbo-16k-0613',
        messages: [{ role: 'user', content: replyInstruction }],
        temperature: 0.7,
    });

    const responseData = await sendPostJson(postData, key);

    const choices = responseData.choices[0].message.content;
    const models = responseData.model;
    const tokens = responseData.usage.prompt_tokens;
    const tokensco = responseData.usage.completion_tokens;
    const money = calculateCost(tokens);
    const moneyw = calculateCosts(tokensco);
    const resultMoney = money + moneyw;
    const mmMoney = resultMoney.toFixed(6);

    return {
        code: 200,
        msg: '获取成功',
        model: models,
        total_money: mmMoney,
        message: instructionMessage,
        answer: choices,
    };
}


// 示例用法:
var instructionMessage = 'https://automa.site';
const key = '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';


const additionalHints = '是什么?他有什么优势和缺点,请分别列给我。有同类产品吗?请分别列给我他们的比较信息';
instructionMessage = instructionMessage + additionalHints;

processInstructions(instructionMessage, key)
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.error(error);
    });

上面的demo代码几个关键点

1. prompt提示词是关键
2. API-KEY 需要确保能用
3. 调用ChatGPT的model和参数也会影响结果(temperature, top_p, presence_penalty, frequency_penalty)

 

demo结果

标签:zh,return,yahoo,replace,instructionMessage,new,const,ChatGPT,搜索引擎
From: https://www.cnblogs.com/hlkawa/p/17626132.html

相关文章

  • 我用ChatGPT的一些实践案例
    推荐使用公式针对复杂的问题,我们可以套用公式:角色+明确任务目标+任务描述/背景信息+输出要求+人工修改(加人味),AI的输出最后还是需要人工来润滑一下的。需要注意的是,跟ChatGPT聊的时候,其实并不需要一开始就提出一个很精确的问题,跟浏览器搜索不同,它是可以记住你上下文的,你完......
  • ChatGPT:为未来的个人和企业提供革命性的对话解决方案
    ChatGPT被认为是未来的个人和企业的革命性对话解决方案,因为它具有以下特点:1.自然流畅的对话:ChatGPT能够以自然的、流畅的方式进行对话,使得与机器的交互更加人性化和易于理解。2.广泛的知识:ChatGPT经过大规模的预训练,可以提供丰富的知识和信息,能够回答各种问题,并提供有用的建议和指......
  • 文心一言 VS 讯飞星火 VS chatgpt (74)-- 算法导论7.2 2题
    二、如果用go语言,当数组A的所有元素都具有相同值时,QUICKSORT的时间复杂度是什么?文心一言:在Go语言中,对一个所有元素都相等的数组进行快速排序(QuickSort)的时间复杂度是O(nlogn)。快速排序是一种分而治之的排序算法,它将一个数组分成两个子数组,然后对这两个子数组进行递归排序。在最......
  • 文心一言 VS 讯飞星火 VS chatgpt (73)-- 算法导论7.1 4题
    四、如何修改QUICKSORT,使得它能够以非递增序进行排序?文心一言:快速排序(Quicksort)是一种常用的排序算法,基于分治策略进行设计。默认情况下,快速排序会以递增序进行排序。若想修改快速排序以实现非递增排序,我们需要调整比较和交换的逻辑。以下是修改后的非递增快速排序的Python代码......
  • 如何更好的使用ChatGPT
    大家都知道,现在市面上的AI工具都是通过一问一答的方式与我们进行互动,其能力非常强,但是至于AI能发挥多大的本事则是取决你如何进行提问,你的提问越精准那么AI工具的答复就会越完美,至于如何进行精准的提问,本篇文章将会以ChatGPT为例给你介绍。点击领取ChatGPT精准提问资料1.ChatGPT的......
  • 文心一言 VS 讯飞星火 VS chatgpt (74)-- 算法导论7.2 2题
    二、如果用go语言,当数组A的所有元素都具有相同值时,QUICKSORT的时间复杂度是什么?文心一言:在Go语言中,对一个所有元素都相等的数组进行快速排序(QuickSort)的时间复杂度是O(nlogn)。快速排序是一种分而治之的排序算法,它将一个数组分成两个子数组,然后对这两个子数组进行递归排序。......
  • chatGPT3.5搭建git
    https://github.com/Chanzhaoyu/chatgpt-webdocker-compose.yamlversion:'3'services:app:image:chenzhaoyu94/chatgpt-web#总是使用latest,更新时重新pull该tag镜像即可ports:-10.0.0.250:3232:3002environment:#二选一......
  • WPF实现类似ChatGPT的逐字打印效果
    背景前一段时间ChatGPT类的应用十分火爆,这类应用在回答用户的问题时逐字打印输出,像极了真人打字回复消息。出于对这个效果的兴趣,决定用WPF模拟这个效果。真实的ChatGPT逐字输出效果涉及其语言生成模型原理以及服务端与前端通信机制,本文不做过多阐述,重点是如何用WPF模拟这个效果......
  • 定制 ChatGPT 以满足您的需求 自定义说明
    推荐:使用NSDT场景编辑器快速助你搭建可二次编辑的3D应用场景20月<>日,OpenAI 宣布他们正在引入带有自定义说明的新流程,以根据您的特定需求定制ChatGPT。什么是自定义说明?新的测试版自定义指令功能旨在通过防止用户在聊天会话之间重复常用指令来帮助用户充分利用ChatGPT。......
  • 爬虫与搜索引擎优化:通过Python爬虫提升搜索排名
    作为一名专业的爬虫程序员,我深知网站的搜索排名对于业务的重要性。在如今竞争激烈的网络世界中,如何让自己的网站在搜索引擎结果中脱颖而出,成为关键。今天,和大家分享一些关于如何通过Python爬虫来提升网站的搜索排名的技巧和实践经验。无论你是在提升自己的网站排名还是优化客户的SE......