### Install Google Cloud Go Package Using go get Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/README.md Commands to install specific Google Cloud Go packages in your project directory. Use go get to fetch the desired package instead of cloning the repository. ```bash cd /my/cloud/project go get cloud.google.com/go/firestore ``` -------------------------------- ### Install OpenCensus Go Library Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/go.opencensus.io/README.md Installs the latest version of the OpenCensus Go library using the go get command. This is the primary step to include OpenCensus in your Go project. ```bash go get -u go.opencensus.io ``` -------------------------------- ### Start and End a Span for Cache Read in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/go.opencensus.io/README.md Illustrates how to start a new span for an operation (e.g., cache read) and ensure it is properly ended using `defer`. This is crucial for tracing request progression and measuring latency within distributed systems. ```go ctx, span := trace.StartSpan(ctx, "cache.Get") defer span.End() // Do work to get from cache. ``` -------------------------------- ### Example I/O timeout error from blocked domain Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/google.golang.org/grpc/README.md Sample error output when golang.org domain is inaccessible. Demonstrates the dial timeout error encountered when go get cannot reach google.golang.org due to network restrictions. ```console go get -u google.golang.org/grpc package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout) ``` -------------------------------- ### Test gRPC Client with Fake Server in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/testing.md This Go test function sets up and runs a test for the `TranslateTextWithConcreteClient` function using a fake gRPC server. It includes steps for creating a listener, starting a gRPC server with the fake implementation, registering the fake server, and then creating a client configured to communicate with this local fake server. Finally, it calls the function under test and asserts the expected outcome. ```go import ( "context" "net" "testing" translate "cloud.google.com/go/translate/apiv3" "google.golang.org/api/option" translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" "google.golang.org/grpc" ) func TestTranslateTextWithConcreteClient(t *testing.T) { ctx := context.Background() // Setup the fake server. fakeTranslationServer := &fakeTranslationServer{} l, err := net.Listen("tcp", "localhost:0") if err != nil { t.Fatal(err) } gsrv := grpc.NewServer() translatepb.RegisterTranslationServiceServer(gsrv, fakeTranslationServer) fakeServerAddr := l.Addr().String() go func() { if err := gsrv.Serve(l); err != nil { panic(err) } }() // Create a client. client, err := translate.NewTranslationClient(ctx, option.WithEndpoint(fakeServerAddr), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithInsecure()), ) if err != nil { t.Fatal(err) } // Run the test. text, err := TranslateTextWithConcreteClient(client, "Hola Mundo", "en-US") if err != nil { t.Fatal(err) } if text != "Hello World" { t.Fatalf("got %q, want Hello World", text) } } ``` -------------------------------- ### Vosk Speech to Text Integration with GoEagi Source: https://github.com/andrewyang17/goeagi/blob/master/README.md This Go code demonstrates integrating the Vosk speech recognition engine with GoEagi. It requires a running Vosk server, which can be started using Docker. The code streams audio to the Vosk server and prints the recognized text. ```go package main import ( "context" "fmt" "os" "github.com/andrewyang17/goEagi" ) func main() { eagi, err := goEagi.New() if err != nil { os.Stdout.WriteString(fmt.Sprintf("error: %v", err)) os.Exit(1) } //use phraseList to list the valid phrases/words. //notes // * if you use a phrase list, Vosk will only detect these words, ignoring any other word // * some Vosk models doesn't support phrase list (I tested with spanish) // * to disable phrase list, leave phraseList empty voskService, err := goEagi.NewVoskService("", "", nil) if err != nil { eagi.Verbose(fmt.Sprintf("error: %v", err)) os.Exit(1) } defer voskService.Close() ctx, cancel := context.WithCancel(context.Background()) defer cancel() bridgeStream := make(chan []byte) defer close(bridgeStream) audioStream := goEagi.StreamAudio(ctx) errCh := voskService.StartStreaming(ctx, bridgeStream) voskResponseCh := voskService.SpeechToTextResponse(ctx) go func(ctx context.Context, eagi *goEagi.Eagi) { for { select { case <-ctx.Done(): return case audio := <-audioStream: if audio.Error != nil { eagi.Verbose(fmt.Sprintf("audio streaming: G error: %v", audio.Error)) cancel() return } bridgeStream <- audio.Stream } } }(ctx, eagi) for { select { case <-ctx.Done(): return case err := <-errCh: eagi.Verbose(fmt.Sprintf("Vosk speech to text response: G error: %v", err)) cancel() return case response := <-voskResponseCh: // you will receive partial data in v.Partial and, if the full text was recognized, you will receive v.Text. eagi.Verbose(fmt.Sprintf("Transcription: %v\n", response.Text)) } } } ``` -------------------------------- ### Get Data from Database using AGI in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Shows how to retrieve a value from the Asterisk database using the 'DatabaseGet' AGI command. The result (Res) is 1 if the key exists and the value is in Dat, otherwise Res is 0. ```go reply, err := session.DatabaseGet("myfamily", "mykey") // Check err and reply.Res and reply.Dat ``` -------------------------------- ### Docker Command to Run Vosk Server Source: https://github.com/andrewyang17/goeagi/blob/master/README.md This Docker command starts a Vosk speech recognition server in detached mode, exposing port 2700. This server can then be connected to by the GoEagi application for real-time speech-to-text processing. ```sh docker run -d -p 2700:2700 alphacep/kaldi-en:latest ``` -------------------------------- ### Initialize AGI Session in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Demonstrates how to create a new AGI session and initialize it by parsing the AGI environment variables. Handles potential errors during initialization. ```go myAgi := agi.New() err := myAgi.Init(nil) if err != nil { log.Fatalf("Error Parsing AGI environment: %v\n", err) } ``` -------------------------------- ### Create Pub/Sub Topic for Storage Notification Tests Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CONTRIBUTING.md Creates a Pub/Sub topic for integration tests of storage notifications and instructs on authorizing the service account as a publisher. Requires manual authorization in the GCP console. ```shell # Creates a PubSub topic for integration tests of storage notifications. $ gcloud beta pubsub topics create go-storage-notification-test # Next, go to the Pub/Sub dashboard in GCP console. Authorize the user # "service-@gs-project-accounts.iam.gserviceaccount.com" # as a publisher to that topic. ``` -------------------------------- ### Create Spanner Instance for Integration Tests Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CONTRIBUTING.md Creates a Spanner instance for integration tests. It's recommended to delete the instance after testing to avoid costs, as Spanner instances are priced by node-hour. ```shell # Creates a Spanner instance for the spanner integration tests. $ gcloud beta spanner instances create go-integration-test --config regional-us-central1 --nodes 10 --description 'Instance for go client test' # NOTE: Spanner instances are priced by the node-hour, so you may want to # delete the instance after testing with 'gcloud beta spanner instances delete'. ``` -------------------------------- ### Get Full Channel Variable using AGI in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Retrieves the value of a channel variable using 'GetFullVariable'. It can handle complex variable names and built-in variables. Success is indicated by Res=1 and the value in Dat. ```go reply, err := session.GetFullVariable("CALLERID(num)") // Check err and reply.Res and reply.Dat ``` -------------------------------- ### Datastore Name Key Creation - Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Demonstrates the creation of a Datastore key using a name, replacing the deprecated NewKey function with NameKey. Namespaces must be explicitly set if used. ```go NameKey(kind, name, parent) ``` -------------------------------- ### Get Channel Status using AGI in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Utilizes the 'ChannelStatus' AGI command to retrieve the status of a specified or current channel. The result codes indicate various channel states like 'Down', 'Ringing', or 'Busy'. ```go reply, err := session.ChannelStatus("SIP/101") // Check err and reply.Res for status codes (0-7) ``` -------------------------------- ### Create Storage Client with JSON Key File Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/README.md Initialize a Google Cloud Storage client using a JSON service account key file for authentication. Pass the credentials file path using option.WithCredentialsFile to the NewClient function. ```go client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json")) ``` -------------------------------- ### Initialize Cloud Client with gRPC Trace Interceptor (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Illustrates initializing a Google Cloud client (e.g., Pub/Sub) with a gRPC dial option that includes a trace interceptor provided by a `trace.Client`. This is the recommended approach after the removal of `trace.EnableGRPCTracing`. ```go c, err := pubsub.NewClient(ctx, "project-id", option.WithGRPCDialOption(grpc.WithUnaryInterceptor(tc.GRPCClientInterceptor()))) ``` -------------------------------- ### Apply Profiler Tags in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/go.opencensus.io/README.md Demonstrates using OpenCensus tags to label profiler samples. This allows associating performance data with specific contexts, such as operating system or user ID, facilitating more granular performance analysis. ```go ctx, err = tag.New(ctx, tag.Insert(osKey, "macOS-10.12.5"), tag.Insert(userIDKey, "fff0989878"), ) if err != nil { log.Fatal(err) } tag.Do(ctx, func(ctx context.Context) { // Do work. // When profiling is on, samples will be // recorded with the key/values from the tag map. }) ``` -------------------------------- ### ReceiveText - Get text string from channel in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Receives text string from channels supporting text reception. Returns -1 in Res for failure or 1 for success, with received string in Dat. Requires text-capable channel type. ```Go func (a *Session) ReceiveText(timeout int) (Reply, error) ``` -------------------------------- ### Create Datastore Indexes for Integration Tests Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CONTRIBUTING.md Creates Datastore indexes from a YAML file for integration tests. It requires the GCLOUD_TESTS_GOLANG_PROJECT_ID and a database ID. The `testdata/index.yaml` file should contain the index definitions. ```shell # Create the indexes for all the databases you want to use in the datastore integration tests. # Use empty string as databaseID or skip database flag for default database. $ gcloud alpha datastore indexes create --database=your-databaseID-1 --project=$GCLOUD_TESTS_GOLANG_PROJECT_ID testdata/index.yaml ``` -------------------------------- ### Get User Input via DTMF using AGI in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Employs the 'GetData' AGI command to prompt the user for DTMF input, optionally specifying timeout and maximum digits. The received digits are stored in the Dat field of the Reply struct. ```go reply, err := session.GetData("prompt-audio", 5000, 4) // Check err and reply.Res (digits) and reply.Dat ``` -------------------------------- ### Stream File using AGI in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Shows how to use the 'StreamFile' AGI command to play a voice prompt to the user. Includes error handling and checking the result of the playback operation. ```go rep, err := myAgi.StreamFile("hello-world", "0123456789") if err != nil { log.Fatalf("AGI reply error: %v\n", err) } if rep.Res == -1 { log.Printf("Error during playback\n") } ``` -------------------------------- ### Stream Audio File with GoEagi Session Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md The StreamFile method sends an audio file over a channel, with an optional offset for playback start. It returns the playback status (0 for completion, digit ASCII value, or -1 for error/disconnect). Music on hold is automatically managed. ```go func (a *Session) StreamFile(file, escape string, offset ...int) (Reply, error) ``` -------------------------------- ### ReceiveChar - Get single character from channel in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Receives one character from channels supporting text reception with timeout. Returns decimal character value in Res if successful, 0 if channel doesn't support text, -1 on error/hang-up. Timeout specified in milliseconds. ```Go func (a *Session) ReceiveChar(timeout int) (Reply, error) ``` -------------------------------- ### Create Storage Client with Default Credentials Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/README.md Initialize a Google Cloud Storage client using Application Default Credentials for authorization. This is the simplest approach and works in many environments without explicit configuration. ```go client, err := storage.NewClient(ctx) ``` -------------------------------- ### Put Data to Database using AGI in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Demonstrates the 'DatabasePut' AGI command for storing key-value pairs in the Asterisk database. Returns 1 on success and 0 on failure. ```go reply, err := session.DatabasePut("myfamily", "mykey", "myvalue") // Check err and reply.Res ``` -------------------------------- ### Build `sys/unix` with Old System (Non-Linux) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/golang.org/x/sys/unix/README.md Generates Go files for the `sys/unix` package using the old build system, which relies on local C header files. Requires bash and Go. Must be run on a system with the target OS and architecture, and unmodified header files. ```bash # Ensure GOOS and GOARCH are set correctly ./mkall.sh # To see the commands that will be run without executing them: ./mkall.sh -n ``` -------------------------------- ### Update RowIterator usage pattern in BigQuery Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Updates the iterator pattern for reading rows. The new RowIterator no longer uses Next(ctx) with separate Get() calls. Instead, Next() accepts the value destination directly and returns an error. Options like RecordsPerRequest and StartIndex are now set via PageInfo() and iterator fields. ```go // Old way for it.Next(ctx) { var vals ValueList if err := it.Get(&vals); err != nil { // TODO: Handle error. } // TODO: use vals. } if err := it.Err(); err != nil { // TODO: Handle error. } // New way for { var vals ValueList err := it.Next(&vals) if err == iterator.Done { break } if err != nil { // TODO: Handle error. } // TODO: use vals. } // Old way for RecordsPerRequest it.RecordsPerRequest(n) // New way it.PageInfo().MaxSize = n // Old way for StartIndex it.StartIndex(i) // New way it.StartIndex = i ``` -------------------------------- ### SpeechCreate - Initialize Speech Recognition Engine Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Creates and initializes a speech recognition object using the specified engine. Returns 1 on success, 0 on error. Must be called before using other speech-related methods. ```Go func (a *Session) SpeechCreate(engine string) (Reply, error) ``` -------------------------------- ### Vosk Offline Speech Recognition in Go Source: https://context7.com/andrewyang17/goeagi/llms.txt Sets up and utilizes the Vosk service for offline speech recognition. It connects to a Vosk server (specified by host and port) and can be configured with an optional phrase list to guide recognition. The service streams audio and returns partial and final transcription results. ```go package main import ( "context" "fmt" "os" "github.com/andrewyang17/goEagi" ) func main() { eagi, err := goEagi.New() if err != nil { os.Stdout.WriteString(fmt.Sprintf("error: %v", err)) os.Exit(1) } // Initialize Vosk service with phrase list voskService, err := goEagi.NewVoskService( "localhost", "2700", []string{"yes", "no", "help", "transfer", "operator"}, ) if err != nil { eagi.Verbose(fmt.Sprintf("error: %v", err)) os.Exit(1) } defer voskService.Close() ctx, cancel := context.WithCancel(context.Background()) defer cancel() bridgeStream := make(chan []byte) // Start audio streaming audioStream := goEagi.StreamAudio(ctx) errCh := voskService.StartStreaming(ctx, bridgeStream) voskResponseCh := voskService.SpeechToTextResponse(ctx) go func(ctx context.Context, eagi *goEagi.Eagi) { for { select { case <-ctx.Done(): return case audio := <-audioStream: if audio.Error != nil { eagi.Verbose(fmt.Sprintf("audio streaming error: %v", audio.Error)) cancel() return } bridgeStream <- audio.Stream } } }(ctx, eagi) // Process Vosk results for { select { case <-ctx.Done(): return case err := <-errCh: eagi.Verbose(fmt.Sprintf("Vosk error: %v", err)) cancel() return case response := <-voskResponseCh: if response.Partial != "" { eagi.Verbose(fmt.Sprintf("Partial: %s", response.Partial)) } if response.Text != "" { eagi.Verbose(fmt.Sprintf("Final: %s", response.Text)) } } } } ``` -------------------------------- ### Pub/Sub: Lightweight Fake for Testing (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Introduces `pubsub/pstest`, a lightweight fake implementation for Google Cloud Pub/Sub, designed for testing purposes. It allows developers to simulate Pub/Sub behavior without needing a live service. This is an experimental feature in v0.18.0. ```Go package main import ( "context" "cloud.google.com/go/pubsub/pstest" "github.com/google/uuid" ) func main() { ctx := context.Background() // Create a new fake Pub/Sub server. server := pstest.NewServer(nil) defer server.Close() // The server's endpoint can be used to configure clients. serverEndpoint := server.Addr // Example: Configure a Pub/Sub client to use the fake server. // (Actual client creation would involve `pubsub.NewClient` with appropriate options pointing to `serverEndpoint`) // You can create topics and subscriptions on the fake server. topicName := "my-test-topic-" + uuid.New().String() t_ , err := server.CreateTopic(ctx, topicName) if err != nil { panic(err) } subName := "my-test-subscription-" + uuid.New().String() t_ , err = server.CreateSubscription(ctx, subName, topicName, 0, 0) if err != nil { panic(err) } // You can then publish messages and subscribe to them using your test client. } ``` -------------------------------- ### Compute Audio Amplitude in Decibels with GoEAGI Source: https://context7.com/andrewyang17/goeagi/llms.txt Calculates the amplitude of an audio stream in decibels (dB). This function is useful for voice activity detection and monitoring audio quality. It takes raw audio bytes as input and returns the computed amplitude and any associated error. The example demonstrates monitoring high and low amplitude levels. ```go package main import ( "context" "fmt" "github.com/andrewyang17/goEagi" ) func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() audioStream := goEagi.StreamAudio(ctx) for { select { case <-ctx.Done(): return case audio := <-audioStream: if audio.Error != nil { fmt.Printf("Error: %v\n", audio.Error) return } // Compute amplitude in decibels amplitude, err := goEagi.ComputeAmplitude(audio.Stream) if err != nil { fmt.Printf("Amplitude computation error: %v\n", err) continue } // Monitor audio levels if amplitude > 50 { fmt.Printf("High amplitude detected: %.2f dB\n", amplitude) } else if amplitude < 20 { fmt.Printf("Low amplitude detected: %.2f dB\n", amplitude) } } } } ``` -------------------------------- ### Initialize EAGI Session with Go Source: https://context7.com/andrewyang17/goeagi/llms.txt Creates a new EAGI session to interface with Asterisk's AGI environment. This is the entry point for all GoEAGI applications. It requires the goEagi package and accesses Asterisk environment variables like agi_callerid and agi_channel. ```go package main import ( "fmt" "os" "github.com/andrewyang17/goEagi" ) func main() { // Initialize EAGI session eagi, err := goEagi.New() if err != nil { os.Stdout.WriteString(fmt.Sprintf("error: %v", err)) os.Exit(1) } // Access Asterisk environment variables callerID := eagi.Env["agi_callerid"] channel := eagi.Env["agi_channel"] eagi.Verbose(fmt.Sprintf("Call from %s on channel %s", callerID, channel)) } ``` -------------------------------- ### Google Text to Speech Rendering and Playback (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/README.md This Go code snippet demonstrates how to use the GoEAGI library to convert text into speech using Google's Text-to-Speech service and then play the generated audio to the Asterisk user. It requires Google Cloud credentials and specifies the content, language code, and voice name as input. The output is an audio file that is streamed back to the caller. ```go package main import ( "strings" "github.com/andrewyang17/goEagi" ) func main() { eagi, err := goEagi.New() if err != nil { os.Stdout.WriteString(fmt.Sprintf("error: %v", err)) os.Exit(1) } content := strings.TrimSpace(eagi.Env["arg_1"]) languageCode := strings.TrimSpace(eagi.Env["arg_2"]) voiceName := strings.TrimSpace(eagi.Env["arg_3"]) tts, err := goEagi.NewGoogleTTS( "", "/tmp/tts", languageCode, voiceName) if err != nil { eagi.Verbose(err.Error()) } audioPath, err := tts.GenerateAudio(content) if err != nil { eagi.Verbose(err.Error()) } _, err = eagi.StreamFile(audioPath, "") if err != nil { eagi.Verbose(err.Error()) } } ``` -------------------------------- ### Configure Gcloud Project and Authentication Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CONTRIBUTING.md Sets the default Google Cloud project and authenticates the gcloud CLI. Requires the GCLOUD_TESTS_GOLANG_PROJECT_ID environment variable to be set. ```shell # Sets the default project in your env. $ gcloud config set project $GCLOUD_TESTS_GOLANG_PROJECT_ID # Authenticates the gcloud tool with your account. $ gcloud auth login ``` -------------------------------- ### Datastore Incomplete Key Creation - Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Illustrates the replacement of NewIncompleteKey with IncompleteKey for creating an incomplete Datastore key. If namespaces are used, they must be set on the returned key. ```go IncompleteKey(kind, parent) ``` -------------------------------- ### Datastore ID Key Creation - Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Shows how to create a Datastore key using an ID, replacing the deprecated NewKey function with IDKey. Namespaces must be explicitly set if used. ```go IDKey(kind, id, parent) ``` -------------------------------- ### Import Google Cloud Client Library Package Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/README.md Basic import statement for the Google Cloud Go client library. This is the foundation package that provides access to Google Cloud Platform services in Go applications. ```go import "cloud.google.com/go" ``` -------------------------------- ### Init - Initialize AGI session in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Initializes a new AGI session with optional bufio.ReadWriter. If nil, uses stdin/stdout for standalone AGI applications. Reads and stores AGI environment variables in Env. Returns error if parsing AGI environment fails. ```Go func (a *Session) Init(rw *bufio.ReadWriter) error ``` -------------------------------- ### Datastore Key Construction with Namespace - Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Shows how to construct a Datastore Key directly using a struct literal, including specifying the namespace. This is possible because all fields of Key are now exported. ```go k := &Key{Kind: "Kind", ID: 37, Namespace: "ns"} ``` -------------------------------- ### Build Command for Azure Speech to Text with Go Source: https://github.com/andrewyang17/goeagi/blob/master/README.md This shell command is used to build a Go project that integrates with Azure Speech to Text. It enables CGO and applies the 'azure' build tag, which is necessary for the Azure Speech SDK to function correctly within the GoEagi framework. ```sh CGO_ENABLED=1 go build -tags azure main.go ``` -------------------------------- ### Replace BucketHandle.List with BucketHandle.Objects (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Demonstrates the transition from the `BucketHandle.List` method to the `BucketHandle.Objects` iterator for listing objects. The new approach uses an iterator pattern, and includes changes for handling pagination tokens and maximum results. ```go ```go // Before // for query != nil { // objs, err := bucket.List(d.ctx, query) // if err != nil { ... } // query = objs.Next // for _, obj := range objs.Results { // fmt.Println(obj) // } // } // After // import "google.golang.org/api/iterator" // ... // iter := bucket.Objects(d.ctx, query) // for { // obj, err := iter.Next() // if err == iterator.Done { // break // } // if err != nil { ... } // fmt.Println(obj) // } // Query.Cursor is replaced by ObjectIterator.PageInfo().Token // Query.MaxResults is replaced by ObjectIterator.PageInfo().MaxSize ``` ``` -------------------------------- ### Configure gRPC Server Interceptor with Trace Client (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Demonstrates how to use a `trace.Client` to provide a gRPC server interceptor. This replaces the older method of directly passing the `trace.GRPCServerInterceptor` function. ```go s := grpc.NewServer(grpc.UnaryInterceptor(tc.GRPCServerInterceptor())) ``` -------------------------------- ### Replace AdminClient.CreateBucket with Client.Bucket.Create (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md This snippet shows the replacement of the older `AdminClient.CreateBucket` method with the newer `Client.Bucket(bucketName).Create` method. The new method is part of the primary `Client` object and requires the project ID. ```go ```go // Before // adminClient.CreateBucket(ctx, bucketName, attrs) // After client.Bucket(bucketName).Create(ctx, projectID, attrs) ``` ``` -------------------------------- ### Create Cloud Storage Bucket for Logging Sink Tests Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CONTRIBUTING.md Creates a Google Cloud Storage bucket with the same name as the project ID and configures the Cloud Logging service account as its owner. This is used for sink integration tests in Cloud Logging. ```shell # Creates a Google Cloud storage bucket with the same name as your test project, # and with the Cloud Logging service account as owner, for the sink # integration tests in logging. $ gsutil mb gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID $ gsutil acl ch -g cloud-logs@google.com:O gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID ``` -------------------------------- ### Create Storage Client with OAuth2 Token Source Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/README.md Initialize a Google Cloud Storage client using a custom oauth2.TokenSource for fine-grained authorization control. Requires golang.org/x/oauth2 package and allows custom token management. ```go tokenSource := ... client, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource)) ``` -------------------------------- ### GetOption - Stream file and prompt for DTMF input in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Streams a file and prompts for DTMF input with optional timeout. Returns received digits in Res and sample offset in Dat. Returns -1 in Res on playback failure. Supports escape characters for early termination. ```Go func (a *Session) GetOption(filename, escape string, timeout ...int) (Reply, error) ``` -------------------------------- ### Syscall Functions in Assembly Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/golang.org/x/sys/unix/README.md Implements system call dispatch in hand-written assembly for the `sys/unix` package. Provides three entry points for different argument counts and low-level access. This file must be implemented for each GOOS/GOARCH pair when porting Go. ```go func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) ``` -------------------------------- ### Import gRPC-Go package Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/google.golang.org/grpc/README.md Basic import statement to add gRPC functionality to Go projects. This single import automatically fetches necessary dependencies when running go build, run, or test commands. ```go import "google.golang.org/grpc" ``` -------------------------------- ### Implement Mock Translate Client in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/testing.md Provides a concrete implementation of the `TranslationClient` interface for testing purposes. This mock client returns a predefined response for the `TranslateText` method. ```go import ( "context" "testing" "github.com/googleapis/gax-go/v2" translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" ) type mockClient struct{} func (*mockClient) TranslateText(_ context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { resp := &translatepb.TranslateTextResponse{ Translations: []*translatepb.Translation{ &translatepb.Translation{ TranslatedText: "Hello World", }, }, } return resp, nil } ``` -------------------------------- ### Enable Key Conversion in Basic or Manual Scaling Handler Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/google.golang.org/appengine/README.md Enables automatic key conversion from cloud.google.com/go/datastore to google.golang.org/appengine/datastore key types for basic and manual scaling environments. This handler should be registered at the /_ah/start endpoint to apply key conversion to all handlers in the service. ```go http.HandleFunc("/_ah/start", func(w http.ResponseWriter, r *http.Request) { datastore.EnableKeyConversion(appengine.NewContext(r)) }) ``` -------------------------------- ### Replace ObjectHandle.CopyTo with ObjectHandle.CopierFrom (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Illustrates the change from `ObjectHandle.CopyTo` to `ObjectHandle.CopierFrom`. This update involves a different method chaining approach to set options before initiating the copy operation. ```go ```go // Before // attrs, err := src.CopyTo(ctx, dst, nil) // After // attrs, err := dst.CopierFrom(src).Run(ctx) // Before with attributes // attrs, err := src.CopyTo(ctx, dst, &storage.ObjectAttrs{ContextType: "text/html"}) // After with attributes // c := dst.CopierFrom(src) // c.ContextType = "text/html" // attrs, err := c.Run(ctx) ``` ``` -------------------------------- ### RecordFile - Record audio to file in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Records audio to specified file with format specification, escape characters, and timeout. Supports optional offset samples and silence detection parameters. Complex return values in Dat vary by case; refer to res_agi.c for details. Negative Res indicates error. ```Go func (a *Session) RecordFile(file, format, escape string, timeout int, params ...interface{}) (Reply, error) ``` -------------------------------- ### Test Function Using Mock Client in Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/testing.md Demonstrates how to write a unit test that uses the `mockClient`. The test calls `TranslateTextWithInterfaceClient` with the mock and asserts the expected output. ```go func TestTranslateTextWithAbstractClient(t *testing.T) { client := &mockClient{} text, err := TranslateTextWithInterfaceClient(client, "Hola Mundo", "en-US") if err != nil { t.Fatal(err) } if text != "Hello World" { t.Fatalf("got %q, want Hello World", text) } } ``` -------------------------------- ### SpeechLoadGrammar - Load Speech Recognition Grammar Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/github.com/zaf/agi/Readme.md Loads a grammar file for speech recognition. Returns 1 on success, 0 on error. Grammar defines the expected speech patterns and phrases to recognize. ```Go func (a *Session) SpeechLoadGrammar(grammar, path string) (Reply, error) ``` -------------------------------- ### Create KMS Keyring and Keys for Encryption Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CONTRIBUTING.md Creates a KMS keyring and two encryption keys (key1, key2). It also sets the GCLOUD_TESTS_GOLANG_KEYRING environment variable and authorizes Google Cloud Storage to use key1 for encryption/decryption. ```shell $ export MY_KEYRING=some-keyring-name $ export MY_LOCATION=global $ export MY_SINGLE_LOCATION=us-central1 # Creates a KMS keyring, in the same location as the default location for your # project's buckets. $ gcloud kms keyrings create $MY_KEYRING --location $MY_LOCATION # Creates two keys in the keyring, named key1 and key2. $ gcloud kms keys create key1 --keyring $MY_KEYRING --location $MY_LOCATION --purpose encryption $ gcloud kms keys create key2 --keyring $MY_KEYRING --location $MY_LOCATION --purpose encryption # Sets the GCLOUD_TESTS_GOLANG_KEYRING environment variable. $ export GCLOUD_TESTS_GOLANG_KEYRING=projects/$GCLOUD_TESTS_GOLANG_PROJECT_ID/locations/$MY_LOCATION/keyRings/$MY_KEYRING # Authorizes Google Cloud Storage to encrypt and decrypt using key1. $ gsutil kms authorize -p $GCLOUD_TESTS_GOLANG_PROJECT_ID -k $GCLOUD_TESTS_GOLANG_KEYRING/cryptoKeys/key1 ``` -------------------------------- ### Configure gRPC Client Interceptor with Trace Client (Go) Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Shows how to configure a gRPC client with a trace interceptor using a `trace.Client`. This method is preferred over directly using `trace.GRPCClientInterceptor`. ```go conn, err := grpc.Dial(srv.Addr, grpc.WithUnaryInterceptor(tc.GRPCClientInterceptor())) ``` -------------------------------- ### Datastore Query with Namespace - Go Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/cloud.google.com/go/CHANGES.md Demonstrates how to specify a namespace for a Datastore query using the Namespace method. This replaces the removed WithNamespace function. ```go q := datastore.NewQuery("Kind").Namespace("ns") ``` -------------------------------- ### Enable gRPC-Go logging via environment variables Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/google.golang.org/grpc/README.md Configure gRPC-Go logging to maximum verbosity for debugging purposes. Sets both verbosity level and severity level to capture detailed transport and connection information. ```bash export GRPC_GO_LOG_VERBOSITY_LEVEL=99 export GRPC_GO_LOG_SEVERITY_LEVEL=info ``` -------------------------------- ### Configure Go module replace for blocked domains Source: https://github.com/andrewyang17/goeagi/blob/master/vendor/google.golang.org/grpc/README.md Workaround for accessing gRPC-Go from regions where golang.org is blocked. Uses Go module replace feature to create aliases and vendor dependencies locally, allowing builds without direct access to blocked domains. ```bash go mod edit -replace=google.golang.org/grpc=github.com/grpc/grpc-go@latest go mod tidy go mod vendor go build -mod=vendor ``` -------------------------------- ### Generate WAV Audio File with GoEAGI Source: https://context7.com/andrewyang17/goeagi/llms.txt Creates a WAV audio file from raw audio byte streams, including necessary headers and metadata. It takes a byte buffer of audio data, a directory path, and a filename as input, returning the path to the generated WAV file. The audio is streamed for a specified duration. ```go package main import ( "context" "fmt" "time" "github.com/andrewyang17/goEagi" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Stream audio for 5 seconds audioStream := goEagi.StreamAudio(ctx) var audioBuffer []byte for { select { case <-ctx.Done(): // Generate WAV file from collected audio audioPath, err := goEagi.GenerateAudio( audioBuffer, "/tmp/recordings/", "call_recording.wav", ) if err != nil { fmt.Printf("Error generating audio: %v\n", err) return } fmt.Printf("Audio saved to: %s\n", audioPath) return case audio := <-audioStream: if audio.Error != nil { fmt.Printf("Error: %v\n", audio.Error) return } audioBuffer = append(audioBuffer, audio.Stream...) } } } ```