githubcopilotapi

package module
v0.0.0-...-fa83a9d Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2024 License: MIT Imports: 16 Imported by: 2

README

GitHub Copilot API

This repository provides an API for GitHub Copilot. The API includes features for completion, embedding, and device authentication.

Table of Contents

Completion

The completion feature allows you to generate code completions.

Example
package main

import (
	"context"
	"fmt"

	copilot "github.com/stong1994/github-copilot-api"
)

func main() {
	client, err := copilot.NewCopilot()
	if err != nil {
		panic(err)
	}
	response, err := client.CreateCompletion(context.Background(), &copilot.CompletionRequest{
		Messages: []copilot.Message{
			{
				Role:    "system",
				Content: "you are a great developer!",
			},
			{
				Role:    "user",
				Content: "give me a code to print hello world with golang",
			},
		},
		StreamingFunc: func(ctx context.Context, chunk []byte) error {
			fmt.Print(string(chunk))
			return nil
		},
	})
	if err != nil {
		panic(err)
	}
	// you can get the content directly
	// fmt.Println(response.Choices[0].Message.Content)
}
Running the Example

To run the example, use the following command:

go run main.go
Expected Output

The output will be similar to this:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

This example demonstrates how to use the GitHub Copilot API to generate a simple "Hello, World!" program in Go.

Embedding

The embedding feature allows you to create embeddings for text.

Example
package main

import (
	"context"
	"fmt"

	copilot "github.com/stong1994/github-copilot-api"
)

func main() {
	client, err := copilot.NewCopilot()
	if err != nil {
		panic(err)
	}
	response, err := client.CreateEmbedding(context.Background(), &copilot.EmbeddingRequest{
		Model: "copilot-text-embedding-ada-002",
		Input: []string{
			"you are a great developer!",
			"thanks for your help",
		},
	})
	if err != nil {
		panic(err)
	}
	for i, embedding := range response.Data {
		fmt.Printf("%d: %v\n", i, embedding)
	}
}
Running the Example
go run main.go
Expected Output
0: {[-0.0026773715 -0.0018009724 0.010035048 ...]}
1: {[-0.0312465 -0.0329363 0.020233147 ...]}

Device Authentication

You can get the GitHub Copilot token with device authentication.

Example
package main

import (
	"context"
	"fmt"

	copilot "github.com/stong1994/github-copilot-api"
)

func main() {
	token, err := copilot.DeviceLogin(context.TODO(), "your GITHUB_CLIENT_ID")
	if err != nil {
		panic(err)
	}
	fmt.Printf("GITHUB_OAUTH_TOKEN is %s, you can set it into environment: export GITHUB_OATUH_TOKEN=%s", token, token)
}

To get the GITHUB_CLIENT_ID, you can follow this blog.

Running the Example
go run main.go
Expected output
Please take this code "B8F8-AF41" to authenticate at https://github.com/login/device.
Press 'y' to continue, or any other key to abort.
y # after enter 'y', you should goto the web page and paste the code above.
Authenticating, please wait...
GITHUB_OAUTH_TOKEN is xxxxx, you can set it into environment: export GITHUB_OAUTH_TOKEN=xxx

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeviceLogin

func DeviceLogin(ctx context.Context, clientID string) (string, error)

Types

type CompletionRequest

type CompletionRequest struct {
	Model       string    `json:"model"`
	Messages    []Message `json:"messages"`
	Temperature float64   `json:"temperature"`
	N           int       `json:"n,omitempty"`
	TopP        float64   `json:"top_p,omitempty"`
	Stream      bool      `json:"stream"`

	// StreamingFunc is a function to be called for each chunk of a streaming response.
	// Return an error to stop streaming early.
	StreamingFunc func(ctx context.Context, chunk []byte) error `json:"-"`
}

CompletionRequest is a request to complete a completion.

type CompletionResponse

type CompletionResponse struct {
	Choices             []CompletionResponseChoice `json:"choices,omitempty"`
	Created             float64                    `json:"created,omitempty"`
	ID                  string                     `json:"id,omitempty"`
	Model               string                     `json:"model,omitempty"`
	PromptFilterResults []struct {
		ContentFilterResults struct {
			Hate struct {
				Filtered bool   `json:"filtered,omitempty"`
				Severity string `json:"severity,omitempty"`
			} `json:"hate,omitempty"`
			SelfHarm struct {
				Filtered bool   `json:"filtered,omitempty"`
				Severity string `json:"severity,omitempty"`
			} `json:"self_harm,omitempty"`
			Sexual struct {
				Filtered bool   `json:"filtered,omitempty"`
				Severity string `json:"severity,omitempty"`
			} `json:"sexual,omitempty"`
			Violence struct {
				Filtered bool   `json:"filtered,omitempty"`
				Severity string `json:"severity,omitempty"`
			} `json:"violence,omitempty"`
		} `json:"content_filter_results,omitempty"`
		PromptIndex float64 `json:"prompt_index,omitempty"`
	} `json:"prompt_filter_results,omitempty"`
	Usage struct {
		CompletionTokens float64 `json:"completion_tokens,omitempty"`
		PromptTokens     float64 `json:"prompt_tokens,omitempty"`
		TotalTokens      float64 `json:"total_tokens,omitempty"`
	} `json:"usage,omitempty"`
}

type CompletionResponseChoice

type CompletionResponseChoice struct {
	ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
	FinishReason         string               `json:"finish_reason,omitempty"`
	Index                float64              `json:"index,omitempty"`
	Message              ResponseMessage      `json:"message,omitempty"`
}

type ContentFilterResults

type ContentFilterResults struct {
	Error struct {
		Code    string `json:"code,omitempty"`
		Message string `json:"message,omitempty"`
	} `json:"error,omitempty"`
	Hate struct {
		Filtered bool   `json:"filtered,omitempty"`
		Severity string `json:"severity,omitempty"`
	} `json:"hate,omitempty"`
	SelfHarm struct {
		Filtered bool   `json:"filtered,omitempty"`
		Severity string `json:"severity,omitempty"`
	} `json:"self_harm,omitempty"`
	Sexual struct {
		Filtered bool   `json:"filtered,omitempty"`
		Severity string `json:"severity,omitempty"`
	} `json:"sexual,omitempty"`
	Violence struct {
		Filtered bool   `json:"filtered,omitempty"`
		Severity string `json:"severity,omitempty"`
	} `json:"violence,omitempty"`
}

type Copilot

type Copilot struct {
	// contains filtered or unexported fields
}

func NewCopilot

func NewCopilot(opts ...Option) (*Copilot, error)

func (*Copilot) CreateCompletion

func (c *Copilot) CreateCompletion(ctx context.Context, payload *CompletionRequest) (*CompletionResponse, error)

func (*Copilot) CreateEmbedding

func (c *Copilot) CreateEmbedding(ctx context.Context, payload *EmbeddingRequest) (*EmbeddingResponse, error)

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer performs a HTTP request.

type EmbeddingRequest

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

type EmbeddingResponse

type EmbeddingResponse struct {
	Data []struct {
		Embedding []float32 `json:"embedding"`
		Index     int       `json:"index"`
	} `json:"data"`
	Usage struct {
		PromptTokens int `json:"prompt_tokens"`
		TotalTokens  int `json:"total_tokens"`
	} `json:"usage"`
}

type Message

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

type Option

type Option func(*Copilot)

Option is an option for the Lingyi client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

func WithClientVersion

func WithClientVersion(version string) Option

func WithCompletionModel

func WithCompletionModel(model string) Option

func WithCopilotIntegrationID

func WithCopilotIntegrationID(copilotintegrationID string) Option

func WithEmbeddingModel

func WithEmbeddingModel(model string) Option

func WithGithubOAuthToken

func WithGithubOAuthToken(githubOAuthToken string) Option

func WithHTTPCopilot

func WithHTTPCopilot(httpclient Doer) Option

func WithOpenAIIntent

func WithOpenAIIntent(openaiIntent string) Option

func WithOpenAIOrganization

func WithOpenAIOrganization(openaiOrganization string) Option

func WithTemperature

func WithTemperature(temperature float64) Option

func WithUserAgent

func WithUserAgent(userAgent string) Option

type ResponseMessage

type ResponseMessage struct {
	Role    *string `json:"role,omitempty"`
	Content string  `json:"content"`
}

type StreamedChatResponsePayload

type StreamedChatResponsePayload struct {
	Choices []struct {
		ContentFilterOffsets struct {
			CheckOffset float64 `json:"check_offset,omitempty"`
			EndOffset   float64 `json:"end_offset,omitempty"`
			StartOffset float64 `json:"start_offset,omitempty"`
		} `json:"content_filter_offsets,omitempty"`
		ContentFilterResults ContentFilterResults `json:"content_filter_results,omitempty"`
		Delta                ResponseMessage      `json:"delta,omitempty"`
		Index                float64              `json:"index,omitempty"`
		FinishReason         string               `json:"finish_reason,omitempty"`
	} `json:"choices,omitempty"`
	Created float64 `json:"created,omitempty"`
	ID      string  `json:"id,omitempty"`
	Error   error   `json:"-"`
}

StreamedChatResponsePayload is a chunk from the stream.

type Token

type Token struct {
	Token     string `json:"token"`
	ExpiresAt int64  `json:"expires_at"`
}

type UserData

type UserData struct {
	OAuthToken string `json:"oauth_token"`
}

Directories

Path Synopsis
completion command
device_login command
embedding command

Jump to

Keyboard shortcuts

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