cozeloop

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2025 License: MIT Imports: 20 Imported by: 26

README

CozeLoop Go SDK

English | 简体中文

Overview

The CozeLoop SDK is a Go client for interacting with CozeLoop platform. Key features:

  • Report trace
  • Get and format prompt

Requirement

  • Go 1.18 or higher

Installation

go get github.com/coze-dev/cozeloop-go

Usage

Initialize

To get started, visit https://loop.coze.cn/console/enterprise/personal/open/oauth/apps and create an OAuth app. Then you can get your owner appid, public key and private key.

Set your environment variables:

export COZELOOP_WORKSPACE_ID=your workspace id
export COZELOOP_JWT_OAUTH_CLIENT_ID=your client id
export COZELOOP_JWT_OAUTH_PRIVATE_KEY=your private key
export COZELOOP_JWT_OAUTH_PUBLIC_KEY_ID=your public key id
Report Trace
func main() {
    ctx, span := loop.StartSpan(ctx, "root", "custom")

    span.SetInput(ctx, "Hello") 
    span.SetOutput(ctx, "World") 
	
    span.Finish(ctx)
	
    loop.Close(ctx)
}
Get Prompt
func main() {
    prompt, err := loop.GetPrompt(ctx, loop.GetPromptParam{PromptKey: "your_prompt_key"})
    messages, err := loop.PromptFormat(ctx, prompt, map[string]any{
        "var1": "your content",
    })
}

You can see more examples here.

Contribution

Please check Contributing for more details.

Security

If you discover a potential security issue in this project, or think you may have discovered a security issue, we ask that you notify Bytedance Security via our security center or vulnerability reporting email.

Please do not create a public GitHub issue.

License

This project is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	// environment keys for loop client
	EnvApiBaseURL          = "COZELOOP_API_BASE_URL"
	EnvWorkspaceID         = "COZELOOP_WORKSPACE_ID"
	EnvApiToken            = "COZELOOP_API_TOKEN"
	EnvJwtOAuthClientID    = "COZELOOP_JWT_OAUTH_CLIENT_ID"
	EnvJwtOAuthPrivateKey  = "COZELOOP_JWT_OAUTH_PRIVATE_KEY"
	EnvJwtOAuthPublicKeyID = "COZELOOP_JWT_OAUTH_PUBLIC_KEY_ID"

	// ComBaseURL = consts.ComBaseURL
	CnBaseURL = consts.CnBaseURL
)
View Source
const (
	SpanFinishEventSpanQueueEntryRate = SpanFinishEvent(consts.SpanFinishEventSpanQueueEntryRate)
	SpanFinishEventFileQueueEntryRate = SpanFinishEvent(consts.SpanFinishEventFileQueueEntryRate)
	SpanFinishEventFlushSpanRate      = SpanFinishEvent(consts.SpanFinishEventFlushSpanRate)
	SpanFinishEventFlushFileRate      = SpanFinishEvent(consts.SpanFinishEventFlushFileRate)
)
View Source
const (
	LogLevelDebug LogLevel = logger.LogLevelDebug
	LogLevelInfo           = logger.LogLevelInfo
	LogLevelWarn           = logger.LogLevelWarn
	LogLevelError          = logger.LogLevelError
	LogLevelFatal          = logger.LogLevelFatal
)

Variables

View Source
var (
	ErrInvalidParam  = consts.ErrInvalidParam
	ErrHeaderParent  = consts.ErrHeaderParent
	ErrRemoteService = consts.ErrRemoteService

	ErrAuthInfoRequired = consts.ErrAuthInfoRequired
	ErrParsePrivateKey  = consts.ErrParsePrivateKey
)
View Source
var DefaultNoopSpan = trace.DefaultNoopSpan

Functions

func Close

func Close(ctx context.Context)

Close close the client. Should be called before program exit.

func Flush

func Flush(ctx context.Context)

Flush Force the reporting of spans in the queue.

func GetPrompt

func GetPrompt(ctx context.Context, param GetPromptParam, options ...GetPromptOption) (*entity.Prompt, error)

GetPrompt get prompt by prompt key and version

func GetWorkspaceID

func GetWorkspaceID() string

GetWorkspaceID return space id

func PromptFormat

func PromptFormat(ctx context.Context, prompt *entity.Prompt, variables map[string]any, options ...PromptFormatOption) (
	messages []*entity.Message, err error,
)

PromptFormat format prompt with variables

func SetDefaultClient added in v0.1.9

func SetDefaultClient(client Client)

func SetLogLevel

func SetLogLevel(level LogLevel)

SetLogLevel set log level. By default, the log level is set to Info. Note that this method is not thread-safe. Should be called before any other method.

func SetLogger

func SetLogger(l Logger)

SetLogger set default logger. By default, the logger is set to stderr. Note that this method is not thread-safe. Should be called before any other method.

func Version

func Version() string

Version returns the version of the loop package.

Types

type APIBasePath added in v0.1.9

type APIBasePath struct {
	TraceSpanUploadPath string
	TraceFileUploadPath string
}

type AuthError

type AuthError = consts.AuthError

type Client

type Client interface {
	// PromptClient interface of prompt client
	PromptClient
	// TraceClient interface of trace client
	TraceClient

	// GetWorkspaceID return workspace id
	GetWorkspaceID() string
	// Close close the client. Should be called before program exit.
	Close(ctx context.Context)
}

Client interface of loop client. The client is thread-safe. **Do not** create multiple instances.

func NewClient

func NewClient(opts ...Option) (Client, error)

NewClient creates a new loop client with the provided options. The client is thread-safe. **Do not** create multiple instances.

type ExecuteOption added in v0.1.12

type ExecuteOption = prompt.ExecuteOption

type ExecuteStreamingOption added in v0.1.12

type ExecuteStreamingOption = prompt.ExecuteStreamingOption

type FinishEventInfo added in v0.1.9

type FinishEventInfo consts.FinishEventInfo

type GetPromptOption

type GetPromptOption func(option *prompt.GetPromptOptions)

type GetPromptParam

type GetPromptParam = prompt.GetPromptParam

type HttpClient

type HttpClient = httpclient.HTTPClient

HttpClient Interface of HttpClient, can use http.DefaultClient

type LogLevel

type LogLevel = logger.LogLevel

LogLevel log level

type Logger

type Logger = logger.Logger

Logger interface for logging

func GetLogger

func GetLogger() Logger

GetLogger get default logger. By default, the logger is set to stderr.

type NoopClient added in v0.1.7

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

NoopClient a noop client

func (*NoopClient) Close added in v0.1.7

func (c *NoopClient) Close(ctx context.Context)

func (*NoopClient) Execute added in v0.1.12

func (c *NoopClient) Execute(ctx context.Context, req *entity.ExecuteParam, options ...ExecuteOption) (entity.ExecuteResult, error)

func (*NoopClient) ExecuteStreaming added in v0.1.12

func (*NoopClient) Flush added in v0.1.7

func (c *NoopClient) Flush(ctx context.Context)

func (*NoopClient) GetPrompt added in v0.1.7

func (c *NoopClient) GetPrompt(ctx context.Context, param GetPromptParam, options ...GetPromptOption) (*entity.Prompt, error)

func (*NoopClient) GetSpanFromContext added in v0.1.7

func (c *NoopClient) GetSpanFromContext(ctx context.Context) Span

func (*NoopClient) GetSpanFromHeader added in v0.1.7

func (c *NoopClient) GetSpanFromHeader(ctx context.Context, header map[string]string) SpanContext

func (*NoopClient) GetWorkspaceID added in v0.1.7

func (c *NoopClient) GetWorkspaceID() string

func (*NoopClient) PromptFormat added in v0.1.7

func (c *NoopClient) PromptFormat(ctx context.Context, prompt *entity.Prompt, variables map[string]any, options ...PromptFormatOption) (messages []*entity.Message, err error)

func (*NoopClient) StartSpan added in v0.1.7

func (c *NoopClient) StartSpan(ctx context.Context, name, spanType string, opts ...StartSpanOption) (context.Context, Span)

type Option

type Option func(o *options)

func WithAPIBasePath added in v0.1.9

func WithAPIBasePath(apiBasePath *APIBasePath) Option

func WithAPIBaseURL

func WithAPIBaseURL(apiBaseURL string) Option

WithAPIBaseURL set api base url. Generally, there's no need to use it. Default is http://api.coze.cn

func WithAPIToken

func WithAPIToken(apiToken string) Option

WithAPIToken set api token. You can get it from https://www.coze.cn/open/oauth/pats **APIToken is just used for testing.** You should use JWTOauth in production.

func WithExporter added in v0.1.7

func WithExporter(e trace.Exporter) Option

WithExporter set custom trace exporter.

func WithHTTPClient

func WithHTTPClient(client HttpClient) Option

WithHTTPClient set http client. All http call inside SDK will use this HttpClient. Default is http.DefaultClient

func WithJWTOAuthClientID

func WithJWTOAuthClientID(clientID string) Option

WithJWTOAuthClientID set jwt oauth client id. You can get it from https://www.coze.cn/open/oauth/apps

func WithJWTOAuthPrivateKey

func WithJWTOAuthPrivateKey(privateKey string) Option

WithJWTOAuthPrivateKey set jwt oauth private key. You can get it from https://www.coze.cn/open/oauth/apps

func WithJWTOAuthPublicKeyID

func WithJWTOAuthPublicKeyID(publicKeyID string) Option

WithJWTOAuthPublicKeyID set jwt oauth public key id. You can get it from https://www.coze.cn/open/oauth/apps

func WithPromptCacheMaxCount

func WithPromptCacheMaxCount(count int) Option

WithPromptCacheMaxCount set prompt cache max count. Default is 100

func WithPromptCacheRefreshInterval

func WithPromptCacheRefreshInterval(interval time.Duration) Option

WithPromptCacheRefreshInterval set prompt cache refresh interval. Default is 10 minute

func WithPromptTrace

func WithPromptTrace(enable bool) Option

WithPromptTrace set whether to report trace when get and format prompt. Default is false

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout set timeout when communicating with loop server. Default is 3s

func WithTraceFinishEventProcessor added in v0.1.9

func WithTraceFinishEventProcessor(f func(ctx context.Context, info *FinishEventInfo)) Option

WithTraceFinishEventProcessor set custom finish event processor, after span finish.

func WithTraceQueueConf added in v0.1.9

func WithTraceQueueConf(conf *TraceQueueConf) Option

func WithTraceTagTruncateConf added in v0.1.9

func WithTraceTagTruncateConf(conf *TagTruncateConf) Option

WithTraceTagTruncateConf set span tag truncate conf.

func WithUltraLargeTraceReport

func WithUltraLargeTraceReport(enable bool) Option

WithUltraLargeTraceReport set whether to report ultra large trace report. Default is false

func WithUploadTimeout

func WithUploadTimeout(timeout time.Duration) Option

WithUploadTimeout set timeout when uploading images or files to loop server. Default is 30s

func WithWorkspaceID

func WithWorkspaceID(workspaceID string) Option

WithWorkspaceID set workspace id.

type PromptClient

type PromptClient interface {
	// GetPrompt get prompt by prompt key and version.
	// if version is not set,  the latest version of the corresponding prompt will be obtained.
	GetPrompt(ctx context.Context, param GetPromptParam, options ...GetPromptOption) (*entity.Prompt, error)
	// PromptFormat format prompt with variables
	PromptFormat(ctx context.Context, prompt *entity.Prompt, variables map[string]any, options ...PromptFormatOption) (messages []*entity.Message, err error)
	// Execute execute prompt and return result
	Execute(ctx context.Context, param *entity.ExecuteParam, options ...ExecuteOption) (entity.ExecuteResult, error)
	// ExecuteStreaming execute prompt in streaming mode and return stream reader
	ExecuteStreaming(ctx context.Context, param *entity.ExecuteParam, options ...ExecuteStreamingOption) (entity.StreamReader[entity.ExecuteResult], error)
}

PromptClient interface of prompt client.

type PromptFormatOption

type PromptFormatOption func(option *prompt.PromptFormatOptions)

type RemoteServiceError

type RemoteServiceError = consts.RemoteServiceError

type Span

type Span interface {
	SpanContext

	// SetTags sets business custom tags.
	SetTags(ctx context.Context, tagKVs map[string]interface{})

	// SetBaggage sets tags and also passes these tags to other downstream spans (assuming
	// the user uses ToHeader and FromHeader to handle header passing between services).
	SetBaggage(ctx context.Context, baggageItems map[string]string)

	// Finish The span will be reported only after an explicit call to Finish.
	// Under the hood, it is actually placed in an asynchronous queue waiting to be reported.
	Finish(ctx context.Context)

	// GetStartTime returns the start time of the Span.
	GetStartTime() time.Time

	// ToHeader Convert the span to headers. Used for cross-process correlation.
	ToHeader() (map[string]string, error)
	// contains filtered or unexported methods
}

Span is the interface for span.

func GetSpanFromContext

func GetSpanFromContext(ctx context.Context) Span

GetSpanFromContext Get the span from the context.

func StartSpan

func StartSpan(ctx context.Context, name, spanType string, opts ...StartSpanOption) (context.Context, Span)

StartSpan Generate a span that automatically links to the previous span in the context. The start time of the span starts counting from the call of StartSpan. The generated span will be automatically written into the context. Subsequent spans that need to be chained should call StartSpan based on the new context.

type SpanContext

type SpanContext interface {
	GetSpanID() string
	GetTraceID() string
	GetBaggage() map[string]string
}

SpanContext is the interface for span Baggage transfer.

func GetSpanFromHeader

func GetSpanFromHeader(ctx context.Context, header map[string]string) SpanContext

GetSpanFromHeader Get the span from the header.

type SpanFinishEvent added in v0.1.9

type SpanFinishEvent consts.SpanFinishEvent

SpanFinishEvent finish inner event

type StartSpanOption

type StartSpanOption = func(o *startSpanOptions)

StartSpanOption is used to set options for the span.

func WithChildOf

func WithChildOf(s SpanContext) StartSpanOption

WithChildOf Set the parent span of the span. This field is optional. If not specified, the parent span will be looked up from the context. If not found, the current span will have no parent.

func WithSpanWorkspaceID added in v0.1.7

func WithSpanWorkspaceID(workspaceID string) StartSpanOption

WithSpanWorkspaceID Set the workspaceID of the span. This field is inner field. You should not set it.

func WithStartNewTrace

func WithStartNewTrace() StartSpanOption

WithStartNewTrace Set the parent span of the span. This field is optional. If specified, start a span of a new trace.

func WithStartTime

func WithStartTime(t time.Time) StartSpanOption

WithStartTime Set the start time of the span. This field is optional. If not specified, the time when StartSpan is called will be used as the default.

type TagTruncateConf added in v0.1.9

type TagTruncateConf trace.TagTruncateConf

type TraceClient

type TraceClient interface {
	// StartSpan Generate a span that automatically links to the previous span in the context.
	// The start time of the span starts counting from the call of StartSpan.
	// The generated span will be automatically written into the context.
	// Subsequent spans that need to be chained should call StartSpan based on the new context.
	StartSpan(ctx context.Context, name, spanType string, opts ...StartSpanOption) (context.Context, Span)
	// GetSpanFromContext Get the span from the context.
	GetSpanFromContext(ctx context.Context) Span
	// GetSpanFromHeader Get the span from the header.
	GetSpanFromHeader(ctx context.Context, header map[string]string) SpanContext
	// Flush Force the reporting of spans in the queue.
	Flush(ctx context.Context)
}

type TraceQueueConf added in v0.1.9

type TraceQueueConf trace.QueueConf

Jump to

Keyboard shortcuts

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