前端调用大模型,如何使用代理?

前言

在Linux和windows系统上,我们会使用export来配置代理

在git上,我们也可以设置http.proxy和https.proxy来配置代理

但是怎么在前端脚手架中使用代理,还是第一次使用。

这里针对openai的调用和fetch的调用进行示例

使用

代理下载

我们需要下载https-proxy-agent这个包,创建一个代理,代码如下:

import { HttpsProxyAgent } from 'https-proxy-agent';  // 使用 ES6 导入语法
const agent = new HttpsProxyAgent('http://127.0.0.1:7890');

在Openai里面这样使用代理

this.llm = new OpenAI({
            apiKey: process.env.OPENAI_API_KEY,
            baseURL: process.env.OPENAI_BASE_URL,
            httpAgent: agent
        });

在fetch里面这样使用代理

需要下载兼容低版本的node-fetch。虽然Agent爆红,但是可以正常运行,可能是IDE依旧以为fetch是默认的那个函数,可能可以通过声明类型文件来进行解决

import fetch from 'node-fetch';  // 引入 fetch(如果在 Node.js 环境中)

const response = await fetch(`${process.env.EMBEDDING_BASE_URL}/embeddings`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${process.env.EMBEDDING_KEY}`,
            },
            body: JSON.stringify({
                model: this.embeddingModel,
                input: document,
                encoding_format: 'float',
            }),
            agent
        });

你可能感兴趣的:(前端,前端)