utils

package
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	VERSION_PREFIX = "vrsn_"
)

Variables

View Source
var (
	HEADER_AUTHORIZATION = "authorization"
	HEADER_PROJECT_ID    = "x-project-id"

	HEADER_API_KEY         = "x-api-key"
	HEADER_AUTH_KEY        = "x-auth-id"
	HEADER_SOURCE_KEY      = "x-client-source"
	HEADER_ENVIRONMENT_KEY = "x-rapida-environment"
	HEADER_REGION_KEY      = "x-rapida-region"

	HEADER_USER_AGENT                = "x-user-agent"
	HEADER_LANGUAGE                  = "x-language"
	HEADER_PLATFORM                  = "x-platform"
	HEADER_SCREEN_WIDTH              = "x-screen-width"
	HEADER_SCREEN_HEIGHT             = "x-screen-height"
	HEADER_WINDOW_WIDTH              = "x-window-width"
	HEADER_WINDOW_HEIGHT             = "x-window-height"
	HEADER_TIMEZONE                  = "x-timezone"
	HEADER_COLOR_DEPTH               = "x-color-depth"
	HEADER_DEVICE_MEMORY             = "x-device-memory"
	HEADER_HARDWARE_CONCURRENCY      = "x-hardware-concurrency"
	HEADER_CONNECTION_TYPE           = "x-connection-type"
	HEADER_CONNECTION_EFFECTIVE_TYPE = "x-connection-effective-type"
	HEADER_COOKIES_ENABLED           = "x-cookies-enabled"
	HEADER_DO_NOT_TRACK              = "x-do-not-track"
	HEADER_REFERRER                  = "x-referrer"
	HEADER_REMOTE_URL                = "x-remote-url"
	HEADER_LATITUDE                  = "x-latitude"
	HEADER_LONGITUDE                 = "x-longitude"
)

Functions

func AnyMapToInterfaceMap added in v0.0.4

func AnyMapToInterfaceMap(anyMap map[string]*anypb.Any) (map[string]interface{}, error)

func AnyToBool added in v0.0.4

func AnyToBool(anyValue *anypb.Any) (bool, error)

func AnyToBytes added in v0.0.4

func AnyToBytes(anyValue *anypb.Any) ([]byte, error)

func AnyToFloat32 added in v0.0.4

func AnyToFloat32(anyValue *anypb.Any) (float32, error)

func AnyToFloat64 added in v0.0.4

func AnyToFloat64(anyValue *anypb.Any) (float64, error)

func AnyToInt added in v0.0.4

func AnyToInt(anyValue *anypb.Any) (int, error)

func AnyToInt32 added in v0.0.4

func AnyToInt32(anyValue *anypb.Any) (int32, error)

func AnyToInt64 added in v0.0.4

func AnyToInt64(anyValue *anypb.Any) (int64, error)

func AnyToInterface added in v0.0.4

func AnyToInterface(anyValue *anypb.Any) (interface{}, error)

func AnyToJSON added in v0.0.4

func AnyToJSON(anyValue *anypb.Any) (map[string]interface{}, error)

func AnyToString added in v0.0.4

func AnyToString(anyValue *anypb.Any) (string, error)

func AnyToUInt32 added in v0.0.4

func AnyToUInt32(anyValue *anypb.Any) (uint32, error)

func AnyToUInt64 added in v0.0.4

func AnyToUInt64(anyValue *anypb.Any) (uint64, error)

func AuthenticateError added in v0.0.4

func AuthenticateError[R any]() (*R, error)

func AverageFloat32 added in v0.0.4

func AverageFloat32(numbers []float32) float32

func BoolToAny added in v0.0.4

func BoolToAny(value bool) (*anypb.Any, error)

func BytesToAny added in v0.0.4

func BytesToAny(value []byte) (*anypb.Any, error)

func Call added in v0.0.4

func Call(ctx context.Context, fn func())

Call executes the provided function and recovers from any panics that occur. If a panic is detected, it is reported and then re-panicked to maintain the error state.

Use this when: - You need to execute a function that might panic - You want to ensure panics are properly logged before propagating - You need context information included in panic reporting

Example:

utils.Call(ctx, func() {
    // code that might panic
})

func CallSafe added in v0.0.4

func CallSafe(ctx context.Context, fn func())

CallSafe executes the provided function and recovers from any panics that occur. Unlike Call, this function will report the panic but not re-panic, allowing execution to continue.

Use this when: - You need to execute a function that might panic - You want to handle the panic gracefully without terminating the current flow - You need the panic logged/reported but want to continue execution

Example:

utils.CallSafe(ctx, func() {
    // potentially dangerous code
})
// execution continues here even if panic occurred

func Cast added in v0.0.4

func Cast(orig interface{}, dst interface{}) error

func DurationToString added in v0.0.4

func DurationToString(v time.Duration) string

func EmbeddingToBase64 added in v0.0.4

func EmbeddingToBase64(embedding []float64) string

func EmbeddingToFloat32 added in v0.0.4

func EmbeddingToFloat32[T float32 | float64](embedding []T) []float32

func EmbeddingToFloat64 added in v0.0.4

func EmbeddingToFloat64[T float32 | float64](embedding []T) []float64

func Error added in v0.0.4

func Error[R any](err error, humanMessage string) (*R, error)

func ErrorWithCode added in v0.0.4

func ErrorWithCode[R any](code int32, err error, humanMessage string) (*R, error)

func Float32ToAny added in v0.0.4

func Float32ToAny(value float32) (*anypb.Any, error)

func Float64SliceToByteArray added in v0.0.4

func Float64SliceToByteArray(data []float64) ([]byte, error)

Convert a slice of float32 to a byte array

func Float64ToAny added in v0.0.4

func Float64ToAny(value float64) (*anypb.Any, error)

func GetAuthId added in v0.0.4

func GetAuthId(ctx context.Context) (*string, bool)

func GetCaseInsensitiveKeyValue added in v0.0.4

func GetCaseInsensitiveKeyValue(cfg map[string]string, key string) (string, bool)

func GetVersionDefinition added in v0.0.4

func GetVersionDefinition(version string) *uint64

func Go added in v0.0.4

func Go(ctx context.Context, fn func())

Go launches the provided function in a new goroutine with panic recovery. If the goroutine panics, the panic will be reported and re-panicked, which will terminate the goroutine but not the entire program.

Use this when: - You need concurrent execution of a function - You want panic handling for the goroutine - You want the panic to be reported before the goroutine terminates

Example:

utils.Go(ctx, func() {
    // concurrent code that might panic
})

func IndexFunc added in v0.0.4

func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int

func Int32ToAny added in v0.0.4

func Int32ToAny(value int32) (*anypb.Any, error)

func Int64ToAny added in v0.0.4

func Int64ToAny(value int64) (*anypb.Any, error)

func IntToString added in v0.0.4

func IntToString(v uint64) string

func InterfaceToAnyValue added in v0.0.4

func InterfaceToAnyValue(v interface{}) (*anypb.Any, error)

func JSONListToAny added in v0.0.4

func JSONListToAny(values []map[string]string) (*anypb.Any, error)

func JSONToAny added in v0.0.4

func JSONToAny(value map[string]interface{}) (*anypb.Any, error)

func JustError added in v0.0.4

func JustError(code int32, err error, humanMessage string) *web_api.Error

func JustSuccess added in v0.0.4

func JustSuccess() (*web_api.BaseResponse, error)

func MapToStruct added in v0.0.4

func MapToStruct(m map[string]interface{}) *structpb.Struct

func MaxUint64 added in v0.0.4

func MaxUint64(a, b uint64) uint64

func MergeMaps added in v0.0.4

func MergeMaps(maps ...map[string]interface{}) map[string]interface{}

func MinUint64 added in v0.0.4

func MinUint64(a, b uint64) uint64

MinUint64 returns the minimum of two uint64 numbers

func OrganizationKnowledgeCollection added in v0.0.4

func OrganizationKnowledgeCollection(orgId, projectId, knowledgeId uint64) string

Collection of knowledge for given organization

func OrganizationObjectPrefix added in v0.0.4

func OrganizationObjectPrefix(orgId, projectId uint64, prefix string) string

object prefix for given org object key

func PaginatedSuccess added in v0.0.4

func PaginatedSuccess[R any, T any](totalItem, currentPage uint32, out T) (*R, error)

func PanicIfNotNil added in v0.0.4

func PanicIfNotNil(ctx context.Context, r any)

PanicIfNotNil reports the provided recovered value if it's not nil, waits for 1 second (allowing logs to flush), then re-panics with formatted info.

Use this when: - You've recovered from a panic and need to decide whether to continue - You want to ensure the panic is properly logged before propagating - You need a brief delay for log systems to process the error

Example:

defer func() { utils.PanicIfNotNil(ctx, recover()) }()

func ProtoJson added in v0.0.4

func ProtoJson(m proto.Message) string

func Ptr

func Ptr[T any](v T) *T

func ReportPanicIfNotNil added in v0.0.4

func ReportPanicIfNotNil(ctx context.Context, r any) bool

ReportPanicIfNotNil reports the provided recovered value if it's not nil and returns true if reporting occurred, false otherwise.

Use this when: - You've recovered from a panic and need to log it - You want to handle the panic without re-panicking - You need to know whether a panic occurred

Example:

if utils.ReportPanicIfNotNil(ctx, recover()) {
    // handle the fact that a panic occurred
}

func Serialize added in v0.0.4

func Serialize(data map[string]interface{}) ([]byte, error)

func StringToAny added in v0.0.4

func StringToAny(value string) (*anypb.Any, error)

func Success added in v0.0.4

func Success[R any, T any](out T) (*R, error)

func ToIntAny added in v0.0.4

func ToIntAny(value int) *anypb.Any

func ToJSONAny added in v0.0.4

func ToJSONAny(value map[string]interface{}) (*anypb.Any, error)

func ToJson added in v0.0.4

func ToJson(obj interface{}) map[string]interface{}

func ToString added in v0.0.4

func ToString(in []string) string

func ToStringAny added in v0.0.4

func ToStringAny(value string) *anypb.Any

func ToUInt64Any added in v0.0.4

func ToUInt64Any(value uint64) *anypb.Any

func UInt32ToAny added in v0.0.4

func UInt32ToAny(value uint32) (*anypb.Any, error)

func UInt64ToAny added in v0.0.4

func UInt64ToAny(value uint64) (*anypb.Any, error)

func Uint64SliceToString added in v0.0.4

func Uint64SliceToString(in []uint64) string

func UnPtr added in v0.0.4

func UnPtr[T any](v *T) T

Types

type AssistantServerEvent added in v0.0.4

type AssistantServerEvent string

func (AssistantServerEvent) Get added in v0.0.4

func (r AssistantServerEvent) Get() string

type AssistantWebhookEvent added in v0.0.4

type AssistantWebhookEvent string
const (
	MessageReceived AssistantWebhookEvent = "message.received"

	MessageSent AssistantWebhookEvent = "message.sent"

	ConversationBegin     AssistantWebhookEvent = "conversation.begin"
	ConversationResume    AssistantWebhookEvent = "conversation.resume"
	ConversationCompleted AssistantWebhookEvent = "conversation.completed"

	ConversationFailed AssistantWebhookEvent = "conversation.failed"
)
const (
	AssistantInitiated AssistantWebhookEvent = "conversation.initiated"
)

func (AssistantWebhookEvent) Get added in v0.0.4

func (r AssistantWebhookEvent) Get() string

type RapidaEnvironment added in v0.0.4

type RapidaEnvironment string
const (
	PRODUCTION  RapidaEnvironment = "production"
	DEVELOPMENT RapidaEnvironment = "development"
)

func FromEnvironmentStr added in v0.0.4

func FromEnvironmentStr(label string) RapidaEnvironment

FromStr returns the corresponding RapidaEnvironment for a given string, or DEVELOPMENT if the string does not match any environment.

func GetClientEnvironment added in v0.0.4

func GetClientEnvironment(ctx context.Context) (RapidaEnvironment, bool)

GetClientEnvironment retrieves the client environment information from the given context. It extracts the environment string from the incoming metadata in the context using the HEADER_ENVIRONMENT_KEY and converts it to a RapidaEnvironment type.

Parameters:

ctx (context.Context): The context from which metadata is extracted. This context
                        typically contains incoming metadata related to the client.

Returns:

RapidaEnvironment: The environment of the client, represented as a RapidaEnvironment
                   constant. The function relies on the `FromEnvironmentStr` function
                   to convert the extracted string to the corresponding RapidaEnvironment
                   value.

Details:

The `metadata.ExtractIncoming(ctx)` function call extracts metadata from the context,
which is then accessed using `Get(HEADER_ENVIRONMENT_KEY)`. This returns a string representing
the environment of the client. The `FromEnvironmentStr` function is used to map this string
to the appropriate RapidaEnvironment constant, ensuring accurate and consistent handling of
client environment information.

func (RapidaEnvironment) Get added in v0.0.4

func (e RapidaEnvironment) Get() string

Get returns the string value of the RapidaEnvironment

type RapidaEvent added in v0.0.4

type RapidaEvent string
const (
	// signals to stop speaking
	// what happend is when user unintentionally interrupt the the voice completly stop
	// pause will make sure that it's not unintentionally interrupted
	TalkPause        RapidaEvent = "talk.onPause"
	TalkInterruption RapidaEvent = "talk.onInterrupt"

	//
	TalkTranscript RapidaEvent = "talk.onTranscript"
	// start and complete
	TalkStart    RapidaEvent = "talk.onStart"
	TalkComplete RapidaEvent = "talk.onComplete"

	TalkGeneration         RapidaEvent = "talk.onGeneration"
	TalkCompleteGeneration RapidaEvent = "talk.onCompleteGeneration"

	TalkStartConversation    RapidaEvent = "talk.onStartConversation"
	TalkCompleteConversation RapidaEvent = "talk.onCompleteConversation"
)

func (RapidaEvent) Get added in v0.0.4

func (r RapidaEvent) Get() string

Get returns the string value of the RapidaStage

type RapidaRegion added in v0.0.4

type RapidaRegion string
const (
	AP  RapidaRegion = "ap"
	US  RapidaRegion = "us"
	EU  RapidaRegion = "eu"
	ALL RapidaRegion = "all"
)

func FromRegionStr added in v0.0.4

func FromRegionStr(label string) RapidaRegion

FromStr returns the corresponding RapidaRegion for a given string, or ALL if the string does not match any region.

func GetClientRegion added in v0.0.4

func GetClientRegion(ctx context.Context) (RapidaRegion, bool)

GetClientRegion retrieves the client region information from the given context. It extracts the region string from the incoming metadata in the context using the HEADER_REGION_KEY and converts it to a RapidaRegion type.

Parameters:

ctx (context.Context): The context from which metadata is extracted. This context
                        typically contains incoming metadata related to the client.

Returns:

RapidaRegion: The region of the client, represented as a RapidaRegion constant.
              The function relies on the `FromRegionStr` function to convert the
              extracted string to the corresponding RapidaRegion value.

Details:

The `metadata.ExtractIncoming(ctx)` function call extracts metadata from the context,
which is then accessed using `Get(HEADER_REGION_KEY)`. This returns a string representing
the region of the client. The `FromRegionStr` function is used to map this string to the
appropriate RapidaRegion constant, facilitating validation and consistent handling of
client region information.

func (RapidaRegion) Get added in v0.0.4

func (r RapidaRegion) Get() string

Get returns the string value of the RapidaRegion

type RapidaSource added in v0.0.4

type RapidaSource string
const (
	WebPlugin RapidaSource = "web-plugin"
	Debugger  RapidaSource = "debugger"
	// api
	SDK       RapidaSource = "sdk"
	PhoneCall RapidaSource = "phone-call"
	Whatsapp  RapidaSource = "whatsapp"
)

func FromSourceStr added in v0.0.4

func FromSourceStr(label string) RapidaSource

FromStr returns the corresponding RapidaSource for a given string, or WebPlugin if the string does not match any source.

func GetClientSource added in v0.0.4

func GetClientSource(ctx context.Context) (RapidaSource, bool)

GetClientSource retrieves the client source information from the given context. It extracts the source string from the incoming metadata in the context using the HEADER_SOURCE_KEY and converts it to a RapidaSource type.

Parameters:

ctx (context.Context): The context from which metadata is extracted. This context
                        typically contains incoming metadata related to the client.

Returns:

RapidaSource: The source of the client, represented as a RapidaSource constant.
              The function relies on the `FromSourceStr` function to convert the
              extracted string to the corresponding RapidaSource value.

Details:

The `metadata.ExtractIncoming(ctx)` function call extracts metadata from the context,
which is then accessed using `Get(HEADER_SOURCE_KEY)`. This returns a string representing
the source of the client. The `FromSourceStr` function is used to map this string to the
appropriate RapidaSource constant, allowing for easier handling and validation of client
source information.

func (RapidaSource) Get added in v0.0.4

func (r RapidaSource) Get() string

Get returns the string value of the RapidaRegion

func (RapidaSource) MarshalJSON added in v0.0.4

func (c RapidaSource) MarshalJSON() ([]byte, error)

type RapidaStage added in v0.0.4

type RapidaStage string
const (
	AuthenticationStage              RapidaStage = "user-authentication"
	TranscriptionStage               RapidaStage = "audio-transcription"
	AssistantIdentificaionStage      RapidaStage = "assistant-identificaion"
	UndefinedStage                   RapidaStage = "undefined"
	QueryFormulationStage            RapidaStage = "query-formulation"
	InformationRetrievalStage        RapidaStage = "information-retrieval"
	DocumentRetrievalStage           RapidaStage = "document-retrieval"
	ContextAugmentationStage         RapidaStage = "context-augmentation"
	TextGenerationStage              RapidaStage = "text-generation"
	ToolCallStage                    RapidaStage = "tool-call"
	ToolExecuteStage                 RapidaStage = "tool-execute"
	OutputEvaluationStage            RapidaStage = "output-evaluation"
	GetToolStage                     RapidaStage = "get-tool"
	ProviderModelIdentificationStage RapidaStage = "model-identificaion"
	CreateMessageStage               RapidaStage = "create-message"
	UpdateMessageStage               RapidaStage = "update-message"
	CreateMessageMetricStage         RapidaStage = "create-message-metric"
)

func (RapidaStage) Get added in v0.0.4

func (r RapidaStage) Get() string

Get returns the string value of the RapidaStage

Jump to

Keyboard shortcuts

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