gigachat

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 26, 2024 License: BSD-3-Clause Imports: 12 Imported by: 6 modules, 5 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Gigachat API

Простой доступ к API Gigachat для Golang.

Установка
go get github.com/saintbyte/gigachat_api
Использование

gigachat "github.com/saintbyte/gigachat_api" Задать переменную среды GIGACHAT_AUTH_DATA из Client Secret в настройка проекта который находиться в пространстве

И подробнее о функциях: https://pkg.go.dev/github.com/saintbyte/gigachat_api

Примеры

см. в директории examples

Documentation

Overview

Package gigachat Предоставляет доступ Gigachat

Этот пакет сделан для того чтоб спрашивать у нейросети gigachat от сбера. Так и делать embedding

Index

Constants

View Source
const (
	GigaChatTokenFileEnv   = "GIGACHAT_TOKEN_FILE"   // Перемеменная среды с путем к файлу с токеном
	GigaChatExpiresFileEnv = "GIGACHAT_EXPIRES_FILE" // Переменная среды с путем к файл где время устревания токена
	GigaChatToken          = "GIGACHAT_TOKEN"        // Или токен берем из окружения
	GigaChatAuthData       = "GIGACHAT_AUTH_DATA"    // Данные дла авторизации чтоб получить токен
	GigaChatOauthUrl       = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth"
)

Авторизауия

View Source
const (
	GigaChatApiHost            = "gigachat.devices.sberbank.ru" //1 - gigachat.devices.sberbank.ru 2  gigachat-preview.devices.sberbank.ru
	GigaChatModelsPath         = "/api/v1/models"
	GigaChatChatCompletionPath = "/api/v1/chat/completions"
	GigaChatEmbeddingsPath     = "/api/v1/embeddings"
)

Ручки API

View Source
const (
	GigaChatModel         = "GigaChat" // GigaChat, GigaChat-Pro, GigaChat-Max Если тестовый хост то GigaChat-Pro-preview
	GigaChatMaxTokens     = 16384
	MaxEmbeddingSize      = 8192
	GigaChatRoleUser      = "user"
	GigaChatRoleSystem    = "system"
	GigaChatRoleAssistant = "assistant"
)

Настройки

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model             string           `json:"model"`
	Messages          []MessageRequest `json:"messages"`
	Stream            bool             `json:"stream"`
	RepetitionPenalty int              `json:"repetition_penalty"`
	Temperature       float32          `json:"temperature"`
	TopP              float32          `json:"top_p"`
	MaxTokens         int              `json:"max_tokens"`
	UpdateInterval    int              `json:"update_interval"`
}

type ChatCompletionResponse

type ChatCompletionResponse struct {
	Choices []ChoicesResponse `json:"choices"`
	Created int               `json:"created"`
	Model   string            `json:"model"`
	Usage   Usage             `json:"usage"`
	Object  string            `json:"object"`
}

type ChoicesResponse

type ChoicesResponse struct {
	Message      MessageRequest `json:"message"`
	Index        int            `json:"index"`
	FinishReason string         `json:"finish_reason"`
}

type EmbeddingsRequest

type EmbeddingsRequest struct {
	Model string   `json:"model"`
	Input []string `json:"input"`
}

type EmbeddingsResponse

type EmbeddingsResponse struct {
	Object string `json:"object"`
	Data   []struct {
		Object    string    `json:"object"`
		Embedding []float32 `json:"embedding"`
		Index     int       `json:"index"`
		Usage     Usage     `json:"usage"`
	} `json:"data"`
	Model string `json:"model"`
}

type Gigachat

type Gigachat struct {
	ApiHost           string
	RepetitionPenalty int
	TopP              float32
	Model             string
	MaxTokens         int
	Temperature       float32
	AuthData          string
}

func NewGigachat

func NewGigachat() *Gigachat

func (*Gigachat) Ask

func (g *Gigachat) Ask(input string) (string, error)

Ask Просто спросить у модели

func (*Gigachat) Auth

func (g *Gigachat) Auth() (int64, string)

Auth Авторизация для получения токена для запросов.

func (*Gigachat) ChatCompletions

func (g *Gigachat) ChatCompletions(messages []MessageRequest) (string, error)

ChatCompletions Сдалать запрос к модели.

func (*Gigachat) Embeddings

func (g *Gigachat) Embeddings(input string) ([]float32, error)

Embeddings получить вектора текста. Ограничение по количеству что-то типа 512.

func (*Gigachat) GetModels

func (g *Gigachat) GetModels() ([]ModelItem, error)

GetModels Получить список моделей.

type MessageRequest

type MessageRequest struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type MessageResponse

type MessageResponse struct {
	Role           string     `json:"role"`
	Content        string     `json:"content"`
	DataForContext []struct{} `json:"data_for_context"`
}

type ModelItem

type ModelItem struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	OwnedBy string `json:"owned_by"`
}

Модель

type ModelsResponse

type ModelsResponse struct {
	Object string      `json:"object"`
	Data   []ModelItem `json:"data"`
}

Ответ на запрос списка моделей

type TokenResponse

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresAt   int64  `json:"expires_at"`
}

Ответ с токенос

type Usage

type Usage struct {
	// Данные об использовании модели.
	PromptTokens     int `json:"prompt_tokens"`               // int32 Количество токенов во входящем сообщении (роль user).
	CompletionTokens int `json:"completion_tokens,omitempty"` // int32  Количество токенов, сгенерированных моделью (роль assistant).
	TotalTokens      int `json:"total_tokens,omitempty"`      //int32 Общее количество токенов.
}

Статистика использования

Directories

Path Synopsis
examples
ask command
function_call command
models command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL