Help us shape the future of Go! Take the 2026 Go Developer Survey

examples

package
v0.87.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package examples contains complete examples of AI-generated workflows.

Index

Constants

View Source
const DynamicStockPriceCheckerSource = `` /* 1444-byte string literal not displayed */

DynamicStockPriceCheckerSource is the stock price checker component written in dynamic format (package component, stdlib only) for the Yaegi interpreter.

View Source
const DynamicTradeExecutorSource = `` /* 872-byte string literal not displayed */

DynamicTradeExecutorSource is the trade executor component written in dynamic format (package component, stdlib only) for the Yaegi interpreter.

View Source
const StockTradingYAML = `` /* 4937-byte string literal not displayed */

StockTradingYAML is the expected workflow YAML config for the stock trading example.

Variables

View Source
var DynamicStockTradingComponents = []ai.ComponentSpec{
	{
		Name:        "stock-price-checker",
		Type:        "stock.price.checker",
		Description: "Fetches current stock price using mock data and detects percentage changes from opening price.",
		Interface:   "dynamic",
		GoCode:      DynamicStockPriceCheckerSource,
	},
	{
		Name:        "trade-executor",
		Type:        "trade.executor",
		Description: "Executes buy or sell trades and returns order confirmation.",
		Interface:   "dynamic",
		GoCode:      DynamicTradeExecutorSource,
	},
}

DynamicStockTradingComponents provides the stock trading components in dynamic format suitable for deployment via the DeployService.

View Source
var StockTradingRequest = ai.GenerateRequest{
	Intent: "Alert me when AAPL stock price changes by 5% from its opening price, then trigger a buy if it drops or a sell if it rises.",
	Context: map[string]string{
		"stock":     "AAPL",
		"threshold": "5%",
		"api":       "Alpha Vantage or similar stock price API",
	},
	Constraints: []string{
		"Poll every minute during market hours",
		"Track percentage change from daily open",
		"Send alerts via messaging system",
		"Use state machine for buy/sell decision flow",
	},
}

StockTradingRequest is the example user intent for stock price monitoring.

View Source
var StockTradingResponse = ai.GenerateResponse{
	Explanation: `This workflow monitors AAPL stock price every minute during market hours.
When the price changes by 5% from the daily open, it triggers a state machine
that decides whether to buy (price dropped) or sell (price rose). Alerts are
sent through the messaging system at each stage.

Components:
1. Schedule trigger polls every minute
2. StockPriceChecker (custom) fetches current price from stock API
3. Event processor detects 5% change threshold
4. State machine manages buy/sell decision flow
5. TradeExecutor (custom) executes the trade
6. Messaging handlers send alerts at each transition`,
	Components: []ai.ComponentSpec{
		{
			Name:        "stock-price-checker",
			Type:        "stock.price.checker",
			Description: "Fetches current stock price from an external API and compares against the daily opening price to detect percentage changes.",
			Interface:   "modular.Module",
			GoCode: `package module

// [DEMO STUB] Replace this entire file with a real stock API integration.
// The CheckPrice method below returns synthetic demo data.
// In production, call a real API (e.g. Alpha Vantage, Polygon.io) and
// parse the JSON response to get live prices.

import (
	"context"
	"math"
	"sync"

	"github.com/GoCodeAlone/modular"
)

type StockPriceChecker struct {
	name       string
	symbol     string
	apiKey     string
	openPrice  float64
	lastPrice  float64
	mu         sync.RWMutex
	httpClient *http.Client
}

func NewStockPriceChecker(name, symbol, apiKey string) *StockPriceChecker {
	return &StockPriceChecker{
		name:       name,
		symbol:     symbol,
		apiKey:     apiKey,
		httpClient: &http.Client{},
	}
}

func (s *StockPriceChecker) Name() string { return s.name }

func (s *StockPriceChecker) RegisterConfig(app modular.Application) {}

func (s *StockPriceChecker) Init(app modular.Application) error {
	return nil
}

func (s *StockPriceChecker) CheckPrice(ctx context.Context) (currentPrice float64, pctChange float64, err error) {
	// [DEMO STUB] This is example/demonstration code only.
	// In production, replace this method body with a real stock API call,
	// e.g. Alpha Vantage: GET /query?function=GLOBAL_QUOTE&symbol=AAPL&apikey=YOUR_KEY
	// For now, synthetic demo prices are returned so the workflow exercises the full decision path.
	s.mu.Lock()
	defer s.mu.Unlock()

	if s.openPrice == 0 {
		// Seed with a realistic demo opening price so callers always get usable data.
		s.openPrice = 182.50 // [DEMO] hardcoded AAPL-like opening price
		s.lastPrice = 182.50
	}

	// Simulate a small price tick so repeated calls show movement.
	s.lastPrice += 0.10 // [DEMO] synthetic +0.10 tick per call

	pctChange = ((s.lastPrice - s.openPrice) / s.openPrice) * 100
	return s.lastPrice, pctChange, nil
}

func (s *StockPriceChecker) SetPrices(openPrice, currentPrice float64) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.openPrice = openPrice
	s.lastPrice = currentPrice
}

func (s *StockPriceChecker) ThresholdExceeded(threshold float64) bool {
	s.mu.RLock()
	defer s.mu.RUnlock()
	if s.openPrice == 0 {
		return false
	}
	pctChange := ((s.lastPrice - s.openPrice) / s.openPrice) * 100
	return math.Abs(pctChange) >= threshold
}

// Ensure interface compliance
var _ modular.Module = (*StockPriceChecker)(nil)
`,
		},
		{
			Name:        "trade-executor",
			Type:        "trade.executor",
			Description: "Executes buy or sell trades based on state machine decisions. Logs trade actions and sends confirmation messages.",
			Interface:   "modular.Module",
			GoCode: `package module

import (
	"context"
	"fmt"
	"time"

	"github.com/GoCodeAlone/modular"
)

type TradeAction string

const (
	TradeActionBuy  TradeAction = "buy"
	TradeActionSell TradeAction = "sell"
	TradeActionHold TradeAction = "hold"
)

type TradeOrder struct {
	Symbol    string      ` + "`json:\"symbol\"`" + `
	Action    TradeAction ` + "`json:\"action\"`" + `
	Quantity  int         ` + "`json:\"quantity\"`" + `
	Price     float64     ` + "`json:\"price\"`" + `
	Timestamp time.Time   ` + "`json:\"timestamp\"`" + `
}

type TradeResult struct {
	OrderID   string      ` + "`json:\"orderId\"`" + `
	Status    string      ` + "`json:\"status\"`" + `
	Action    TradeAction ` + "`json:\"action\"`" + `
	Price     float64     ` + "`json:\"price\"`" + `
	Timestamp time.Time   ` + "`json:\"timestamp\"`" + `
}

type TradeExecutor struct {
	name   string
	logger modular.Logger
}

func NewTradeExecutor(name string) *TradeExecutor {
	return &TradeExecutor{name: name}
}

func (t *TradeExecutor) Name() string { return t.name }

func (t *TradeExecutor) RegisterConfig(app modular.Application) {}

func (t *TradeExecutor) Init(app modular.Application) error {
	t.logger = app.Logger()
	return nil
}

func (t *TradeExecutor) Execute(ctx context.Context, order TradeOrder) (*TradeResult, error) {
	t.logger.Info(fmt.Sprintf("Executing %s order for %s: qty=%d price=%.2f",
		order.Action, order.Symbol, order.Quantity, order.Price))

	// [DEMO STUB] Returns a simulated order confirmation.
	// In production, replace this with a real brokerage API call (e.g. Alpaca, TD Ameritrade).
	return &TradeResult{
		OrderID:   fmt.Sprintf("ORD-%d", time.Now().UnixNano()),
		Status:    "executed",
		Action:    order.Action,
		Price:     order.Price,
		Timestamp: time.Now(),
	}, nil
}

var _ modular.Module = (*TradeExecutor)(nil)
`,
		},
	},
}

StockTradingResponse is the expected generated response for the stock trading example. This serves as a reference for tests and documentation.

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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