申请google gemini免费apikey打造本地多模态ai聊天助手笔记

申请google gemini免费apikey打造本地多模态ai聊天助手笔记

800_auto

google最近更新了gemini-1.5-pro,200万的上下文tokens,听说效果直接秒杀gpt4o等主流大模型,而且还是免费可申请apikey使用,今天我也来申请一个:

先申请一个gemini的apikey:申请地址:https://aistudio.google.com/app/apikey?pli=1

800_auto

gemini提示词库:https://ai.google.dev/gemini-api/prompts?hl=zh-cn

gemini api文档:https://ai.google.dev/gemini-api/docs/get-started/tutorial?lang=python&hl=zh-cn

由于国外的封锁,所有国内无法直接访问gemini的api接口,cloudflare worker由于国内访问的是香港的worker,所有也在被限制了

现在有两种解决办法:

1、使用vertex ai来调用gemini api

申请教程可以参考:点击打开链接

具体的worker代码和客户端调用代码我放在文章后面。

2、在未限制ip的国家租用虚拟主机,自己搭建gemini代理

去阿里云上购买一个其他国家的ecs服务器,例如日本,然后安装nodejs,在nodejs下运行以下代码搭建代理

const http = require('http');
const httpProxy = require('http-proxy');

// 创建一个代理服务器实例
const proxy = httpProxy.createProxyServer({
    ws: true,
    changeOrigin: true,
    secure: false
});

// 修改请求头中的 Host 字段
proxy.on('proxyReq', (proxyReq, req, res, options) => {
    proxyReq.setHeader('Host', 'generativelanguage.googleapis.com');
});

// 创建一个HTTP服务器
const server = http.createServer((req, res) => {
    // 设置目标服务器地址
    const target = 'https://generativelanguage.googleapis.com';

    // 添加跨域头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    // 处理预检请求
    if (req.method === 'OPTIONS') {
        res.writeHead(204);
        res.end();
        return;
    }

    // 代理请求到目标服务器
    proxy.web(req, res, { target });
});

// 处理代理服务器错误
proxy.on('error', (err, req, res) => {
    console.error('Proxy error:', err);
    res.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    res.end('Something went wrong. Please try again later.');
});

// 启动服务器,监听端口8000
server.listen(8000, "0.0.0.0", () => {
    console.log('Proxy server is running on http://localhost:8000');
});

客户端调用代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />
    <title>BFW NEW PAGE</title>


</head>
<body>

    <script type="module">
     const API_KEY = "";//官网

const response  =  await fetch(`https://代理服务器域名/v1beta/models/gemini-1.5-flash:streamGenerateContent?alt=sse&key=`+API_KEY, {
body: JSON.stringify({

    "contents": [
        {
            "role": "user",
            "parts": [
                {"text":"hello"}
            ]
        }
    ],
    "generationConfig": {
        "maxOutputTokens": 8192,
        "temperature": 1,
        "topP": 0.95,
    },
    "safetySettings": [
        {
            "category": "HARM_CATEGORY_HATE_SPEECH",
            "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
            "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
            "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
            "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
            "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        },
        {
            "category": "HARM_CATEGORY_HARASSMENT",
            "threshold": "BLOCK_MEDIUM_AND_ABOVE"
        }
    ],
       
       
    }),
    method: 'POST',
    headers: {
        'content-type': 'application/json',
      

    }
    });
        
        
       
			
  // 检查响应状态码
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}${response.statusText}`);
    }
    
    // 将响应体设置为可读流,并逐步输出数据到可写流
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    const textDecoder = new TextEncoder();
  
    while (true) {
      const { done, value } =await reader.read();
      if (done) {
        break;
      }
 const chunk = decoder.decode(value);


const lines = chunk.split('\n').filter(line => line.trim() !== '');

            // Process each line
            for (const line of lines) {
                
              
                // Remove the "data: " prefix from the line
                const message = line.replace(/^data: /, '');
               // console.log(message)
 const content = JSON.parse(message).candidates[0].content.parts[0].text;
 if(content!=undefined){
      console.log(content)
 }

            }
            
            
            

    }

    </script>
    看console
</body>
</html>
		

点击查看cloudflare worker与浏览器调用代码

{{collectdata}}

网友评论