Gemini 实战

谷歌的 Gemini 已对外开放,虽然完全比不上他宣传的那么叼,但不妨碍我们尝试把玩。 本文的目的是能够在本地调通 Gemini 的 api 接口

效果

先看一下效果

img.png

获取 api key

https://ai.google.dev img_1.png

img_2.png

img_3.png

img_4.png

反向代理

https://vercel.com/

用国内手机号就能注册

https://github.com/antergone/palm-proxy

直接点击 Deploy 按钮,完成后续操作就行了

Hello Gemini

跑的时候,直接使用官方的库不太好使,自己照着复制粘贴了一套。

import (
	"fmt"
	"testing"

	jsoniter "github.com/json-iterator/go"
	"github.com/stretchr/testify/assert"
	"github.com/weirwei/ikit/ihttp"
	"github.com/weirwei/ikit/iutil"
)

type AutoGenerated struct {
	Candidates     []Candidates   `json:"candidates"`
	PromptFeedback PromptFeedback `json:"promptFeedback"`
}

type SafetyRatings struct {
	Category    string `json:"category"`
	Probability string `json:"probability"`
}
type Candidates struct {
	Content       Content         `json:"content"`
	FinishReason  string          `json:"finishReason"`
	Index         int             `json:"index"`
	SafetyRatings []SafetyRatings `json:"safetyRatings"`
}
type PromptFeedback struct {
	SafetyRatings []SafetyRatings `json:"safetyRatings"`
}

// /////
type GenerateContentRequest struct {
	Model    string     `json:"model,omitempty"`
	Contents []*Content `json:"contents,omitempty"`
}

type Content struct {
	Parts []*Part `json:"parts,omitempty"`
	Role  string  `json:"role,omitempty"`
}

type Part struct {
	Text string `json:"text"`
}

const apiKey = "xxxxxxxx" // 这里写你自己申请的 api key

func Gemini(req GenerateContentRequest) (*AutoGenerated, error) {
	_url := "https://palm-proxy-blush-two.vercel.app/v1/models/gemini-pro:generateContent"
	requestBody := make(map[string]interface{})
	var result AutoGenerated
	err := iutil.StructMap(&req, requestBody)
	if err != nil {
		return nil, err
	}
	resp, err := ihttp.POST(&ihttp.Options{
		URL:         fmt.Sprintf("%s?key=%s", _url, apiKey),
		RequestBody: requestBody,
		Encode:      ihttp.EncodeJson,
		Retry:       0,
		Timeout:     300000,
	})
	if err != nil {
		return nil, err
	}
	err = jsoniter.UnmarshalFromString(resp.ResponseBody, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

func TestGemini(t *testing.T) {
	req := GenerateContentRequest{
		Contents: []*Content{
			{
				Parts: []*Part{
					{
						Text: "你好!文心一言",
					},
				},
				Role: "user",
			},
		},
	}
	res, err := Gemini(req)
	assert.Nil(t, err)
	t.Log(iutil.ToJson(res))
}

这样算是跑通了,后续就直接对着官方文档研究吧