{"modulePath":"github.com/GoCodeAlone/workflow","version":"v0.87.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package examples\n\nPackage examples contains complete examples of AI-generated workflows.\n\n## Constants\n\n```go\nconst DynamicStockPriceCheckerSource = `package component\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/rand\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar openPrice float64\nvar lastPrice float64\n\nfunc Name() string {\n\treturn \"stock-price-checker\"\n}\n\nfunc Init(services map[string]interface{}) error {\n\t// Seed with a mock opening price\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\topenPrice = 150.0 + r.Float64()*10.0\n\tlastPrice = openPrice\n\treturn nil\n}\n\nfunc Execute(ctx context.Context, params map[string]interface{}) (map[string]interface{}, error) {\n\tsymbol, _ := params[\"symbol\"].(string)\n\tif symbol == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing required parameter: symbol\")\n\t}\n\n\tthresholdVal, _ := params[\"threshold\"].(float64)\n\tif thresholdVal == 0 {\n\t\tthresholdVal = 5.0\n\t}\n\n\t// Simulate price movement\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tchange := (r.Float64() - 0.5) * 4.0\n\tlastPrice = lastPrice + change\n\n\tpctChange := ((lastPrice - openPrice) / openPrice) * 100.0\n\texceeded := math.Abs(pctChange) \u003e= thresholdVal\n\n\tsignal := \"hold\"\n\tif exceeded \u0026\u0026 pctChange \u003c 0 {\n\t\tsignal = \"buy\"\n\t} else if exceeded \u0026\u0026 pctChange \u003e 0 {\n\t\tsignal = \"sell\"\n\t}\n\n\treturn map[string]interface{}{\n\t\t\"symbol\":     strings.ToUpper(symbol),\n\t\t\"openPrice\":  fmt.Sprintf(\"%.2f\", openPrice),\n\t\t\"lastPrice\":  fmt.Sprintf(\"%.2f\", lastPrice),\n\t\t\"pctChange\":  fmt.Sprintf(\"%.2f\", pctChange),\n\t\t\"exceeded\":   exceeded,\n\t\t\"signal\":     signal,\n\t\t\"timestamp\":  time.Now().Format(time.RFC3339),\n\t}, nil\n}\n`\n```\nDynamicStockPriceCheckerSource is the stock price checker component written in dynamic format (package component, stdlib only) for the Yaegi interpreter.\n\n```go\nconst DynamicTradeExecutorSource = `package component\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc Name() string {\n\treturn \"trade-executor\"\n}\n\nfunc Init(services map[string]interface{}) error {\n\treturn nil\n}\n\nfunc Execute(ctx context.Context, params map[string]interface{}) (map[string]interface{}, error) {\n\taction, _ := params[\"action\"].(string)\n\tif action == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing required parameter: action\")\n\t}\n\tsymbol, _ := params[\"symbol\"].(string)\n\tif symbol == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing required parameter: symbol\")\n\t}\n\tprice, _ := params[\"price\"].(string)\n\n\torderID := fmt.Sprintf(\"ORD-%d\", time.Now().UnixNano())\n\n\treturn map[string]interface{}{\n\t\t\"orderId\":   orderID,\n\t\t\"status\":    \"executed\",\n\t\t\"action\":    strings.ToLower(action),\n\t\t\"symbol\":    strings.ToUpper(symbol),\n\t\t\"price\":     price,\n\t\t\"timestamp\": time.Now().Format(time.RFC3339),\n\t}, nil\n}\n`\n```\nDynamicTradeExecutorSource is the trade executor component written in dynamic format (package component, stdlib only) for the Yaegi interpreter.\n\n```go\nconst StockTradingYAML = `# Stock Trading Alert Workflow\n# Monitors AAPL price, alerts on 5% change, triggers buy/sell decisions\n\nmodules:\n  # HTTP server for webhook/API access\n  - name: http-server\n    type: http.server\n    config:\n      address: \":8080\"\n\n  - name: api-router\n    type: http.router\n    dependsOn:\n      - http-server\n\n  - name: trade-api\n    type: api.handler\n    config:\n      resourceName: \"trades\"\n    dependsOn:\n      - api-router\n\n  # Stock price monitoring (custom component)\n  - name: price-checker\n    type: stock.price.checker\n    config:\n      symbol: \"AAPL\"\n      threshold: 5.0\n\n  # Event processing for price change detection\n  - name: price-event-processor\n    type: event.processor\n    config:\n      bufferSize: 500\n      cleanupInterval: \"1m\"\n\n  # Messaging for alerts\n  - name: alert-broker\n    type: messaging.broker\n\n  - name: price-alert-handler\n    type: messaging.handler\n    config:\n      description: \"Sends price change alerts\"\n\n  - name: trade-notification-handler\n    type: messaging.handler\n    config:\n      description: \"Sends trade execution notifications\"\n\n  # State machine for buy/sell decisions\n  - name: trade-decision-engine\n    type: statemachine.engine\n    config:\n      description: \"Manages buy/sell decision flow\"\n\n  # Trade execution (custom component)\n  - name: trade-executor\n    type: trade.executor\n    config:\n      description: \"Executes trades via brokerage API\"\n\nworkflows:\n  # HTTP routes\n  http:\n    routes:\n      - method: GET\n        path: /api/trades\n        handler: trade-api\n      - method: POST\n        path: /api/trades\n        handler: trade-api\n\n  # Event processing for price changes\n  event:\n    processor: price-event-processor\n    patterns:\n      - patternId: \"price-drop-alert\"\n        eventTypes: [\"stock.price.drop\"]\n        windowTime: \"1m\"\n        condition: \"count\"\n        minOccurs: 1\n      - patternId: \"price-rise-alert\"\n        eventTypes: [\"stock.price.rise\"]\n        windowTime: \"1m\"\n        condition: \"count\"\n        minOccurs: 1\n    handlers:\n      - patternId: \"price-drop-alert\"\n        handler: price-alert-handler\n      - patternId: \"price-rise-alert\"\n        handler: price-alert-handler\n\n  # Messaging subscriptions\n  messaging:\n    subscriptions:\n      - topic: price-alerts\n        handler: price-alert-handler\n      - topic: trade-notifications\n        handler: trade-notification-handler\n\n  # State machine for trade decisions\n  statemachine:\n    engine: trade-decision-engine\n    definitions:\n      - name: trade-decision\n        description: \"Stock trade decision workflow\"\n        initialState: \"monitoring\"\n        states:\n          monitoring:\n            description: \"Monitoring price changes\"\n            isFinal: false\n          threshold_exceeded:\n            description: \"Price threshold exceeded, evaluating\"\n            isFinal: false\n          buy_signal:\n            description: \"Buy signal detected (price dropped)\"\n            isFinal: false\n          sell_signal:\n            description: \"Sell signal detected (price rose)\"\n            isFinal: false\n          executing_trade:\n            description: \"Trade is being executed\"\n            isFinal: false\n          trade_completed:\n            description: \"Trade executed successfully\"\n            isFinal: true\n          trade_failed:\n            description: \"Trade execution failed\"\n            isFinal: true\n            isError: true\n          cooldown:\n            description: \"Cooling down after trade\"\n            isFinal: false\n        transitions:\n          detect_change:\n            fromState: \"monitoring\"\n            toState: \"threshold_exceeded\"\n          signal_buy:\n            fromState: \"threshold_exceeded\"\n            toState: \"buy_signal\"\n          signal_sell:\n            fromState: \"threshold_exceeded\"\n            toState: \"sell_signal\"\n          execute_buy:\n            fromState: \"buy_signal\"\n            toState: \"executing_trade\"\n          execute_sell:\n            fromState: \"sell_signal\"\n            toState: \"executing_trade\"\n          trade_success:\n            fromState: \"executing_trade\"\n            toState: \"trade_completed\"\n          trade_error:\n            fromState: \"executing_trade\"\n            toState: \"trade_failed\"\n          resume_monitoring:\n            fromState: \"trade_completed\"\n            toState: \"cooldown\"\n          cooldown_complete:\n            fromState: \"cooldown\"\n            toState: \"monitoring\"\n    hooks:\n      - workflowType: \"trade-decision\"\n        transitions: [\"execute_buy\", \"execute_sell\"]\n        handler: \"trade-executor\"\n      - workflowType: \"trade-decision\"\n        toStates: [\"trade_completed\", \"trade_failed\"]\n        handler: \"trade-notification-handler\"\n\ntriggers:\n  # Poll every minute during market hours\n  schedule:\n    jobs:\n      - cron: \"* 9-16 * * 1-5\"\n        workflow: \"trade-decision\"\n        action: \"check_price\"\n        params:\n          symbol: \"AAPL\"\n          threshold: 5.0\n`\n```\nStockTradingYAML is the expected workflow YAML config for the stock trading example.\n\n## Variables\n\n```go\nvar DynamicStockTradingComponents = []ai.ComponentSpec{\n\t{\n\t\tName:        \"stock-price-checker\",\n\t\tType:        \"stock.price.checker\",\n\t\tDescription: \"Fetches current stock price using mock data and detects percentage changes from opening price.\",\n\t\tInterface:   \"dynamic\",\n\t\tGoCode:      DynamicStockPriceCheckerSource,\n\t},\n\t{\n\t\tName:        \"trade-executor\",\n\t\tType:        \"trade.executor\",\n\t\tDescription: \"Executes buy or sell trades and returns order confirmation.\",\n\t\tInterface:   \"dynamic\",\n\t\tGoCode:      DynamicTradeExecutorSource,\n\t},\n}\n```\nDynamicStockTradingComponents provides the stock trading components in dynamic format suitable for deployment via the DeployService.\n\n```go\nvar StockTradingRequest = ai.GenerateRequest{\n\tIntent: \"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.\",\n\tContext: map[string]string{\n\t\t\"stock\":     \"AAPL\",\n\t\t\"threshold\": \"5%\",\n\t\t\"api\":       \"Alpha Vantage or similar stock price API\",\n\t},\n\tConstraints: []string{\n\t\t\"Poll every minute during market hours\",\n\t\t\"Track percentage change from daily open\",\n\t\t\"Send alerts via messaging system\",\n\t\t\"Use state machine for buy/sell decision flow\",\n\t},\n}\n```\nStockTradingRequest is the example user intent for stock price monitoring.\n\n```go\nvar StockTradingResponse = ai.GenerateResponse{\n\tExplanation: `This workflow monitors AAPL stock price every minute during market hours.\nWhen the price changes by 5% from the daily open, it triggers a state machine\nthat decides whether to buy (price dropped) or sell (price rose). Alerts are\nsent through the messaging system at each stage.\n\nComponents:\n1. Schedule trigger polls every minute\n2. StockPriceChecker (custom) fetches current price from stock API\n3. Event processor detects 5% change threshold\n4. State machine manages buy/sell decision flow\n5. TradeExecutor (custom) executes the trade\n6. Messaging handlers send alerts at each transition`,\n\tComponents: []ai.ComponentSpec{\n\t\t{\n\t\t\tName:        \"stock-price-checker\",\n\t\t\tType:        \"stock.price.checker\",\n\t\t\tDescription: \"Fetches current stock price from an external API and compares against the daily opening price to detect percentage changes.\",\n\t\t\tInterface:   \"modular.Module\",\n\t\t\tGoCode: `package module\n\n// [DEMO STUB] Replace this entire file with a real stock API integration.\n// The CheckPrice method below returns synthetic demo data.\n// In production, call a real API (e.g. Alpha Vantage, Polygon.io) and\n// parse the JSON response to get live prices.\n\nimport (\n\t\"context\"\n\t\"math\"\n\t\"sync\"\n\n\t\"github.com/GoCodeAlone/modular\"\n)\n\ntype StockPriceChecker struct {\n\tname       string\n\tsymbol     string\n\tapiKey     string\n\topenPrice  float64\n\tlastPrice  float64\n\tmu         sync.RWMutex\n\thttpClient *http.Client\n}\n\nfunc NewStockPriceChecker(name, symbol, apiKey string) *StockPriceChecker {\n\treturn \u0026StockPriceChecker{\n\t\tname:       name,\n\t\tsymbol:     symbol,\n\t\tapiKey:     apiKey,\n\t\thttpClient: \u0026http.Client{},\n\t}\n}\n\nfunc (s *StockPriceChecker) Name() string { return s.name }\n\nfunc (s *StockPriceChecker) RegisterConfig(app modular.Application) {}\n\nfunc (s *StockPriceChecker) Init(app modular.Application) error {\n\treturn nil\n}\n\nfunc (s *StockPriceChecker) CheckPrice(ctx context.Context) (currentPrice float64, pctChange float64, err error) {\n\t// [DEMO STUB] This is example/demonstration code only.\n\t// In production, replace this method body with a real stock API call,\n\t// e.g. Alpha Vantage: GET /query?function=GLOBAL_QUOTE\u0026symbol=AAPL\u0026apikey=YOUR_KEY\n\t// For now, synthetic demo prices are returned so the workflow exercises the full decision path.\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif s.openPrice == 0 {\n\t\t// Seed with a realistic demo opening price so callers always get usable data.\n\t\ts.openPrice = 182.50 // [DEMO] hardcoded AAPL-like opening price\n\t\ts.lastPrice = 182.50\n\t}\n\n\t// Simulate a small price tick so repeated calls show movement.\n\ts.lastPrice += 0.10 // [DEMO] synthetic +0.10 tick per call\n\n\tpctChange = ((s.lastPrice - s.openPrice) / s.openPrice) * 100\n\treturn s.lastPrice, pctChange, nil\n}\n\nfunc (s *StockPriceChecker) SetPrices(openPrice, currentPrice float64) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.openPrice = openPrice\n\ts.lastPrice = currentPrice\n}\n\nfunc (s *StockPriceChecker) ThresholdExceeded(threshold float64) bool {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tif s.openPrice == 0 {\n\t\treturn false\n\t}\n\tpctChange := ((s.lastPrice - s.openPrice) / s.openPrice) * 100\n\treturn math.Abs(pctChange) \u003e= threshold\n}\n\n// Ensure interface compliance\nvar _ modular.Module = (*StockPriceChecker)(nil)\n`,\n\t\t},\n\t\t{\n\t\t\tName:        \"trade-executor\",\n\t\t\tType:        \"trade.executor\",\n\t\t\tDescription: \"Executes buy or sell trades based on state machine decisions. Logs trade actions and sends confirmation messages.\",\n\t\t\tInterface:   \"modular.Module\",\n\t\t\tGoCode: `package module\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/GoCodeAlone/modular\"\n)\n\ntype TradeAction string\n\nconst (\n\tTradeActionBuy  TradeAction = \"buy\"\n\tTradeActionSell TradeAction = \"sell\"\n\tTradeActionHold TradeAction = \"hold\"\n)\n\ntype TradeOrder struct {\n\tSymbol    string      ` + \"`json:\\\"symbol\\\"`\" + `\n\tAction    TradeAction ` + \"`json:\\\"action\\\"`\" + `\n\tQuantity  int         ` + \"`json:\\\"quantity\\\"`\" + `\n\tPrice     float64     ` + \"`json:\\\"price\\\"`\" + `\n\tTimestamp time.Time   ` + \"`json:\\\"timestamp\\\"`\" + `\n}\n\ntype TradeResult struct {\n\tOrderID   string      ` + \"`json:\\\"orderId\\\"`\" + `\n\tStatus    string      ` + \"`json:\\\"status\\\"`\" + `\n\tAction    TradeAction ` + \"`json:\\\"action\\\"`\" + `\n\tPrice     float64     ` + \"`json:\\\"price\\\"`\" + `\n\tTimestamp time.Time   ` + \"`json:\\\"timestamp\\\"`\" + `\n}\n\ntype TradeExecutor struct {\n\tname   string\n\tlogger modular.Logger\n}\n\nfunc NewTradeExecutor(name string) *TradeExecutor {\n\treturn \u0026TradeExecutor{name: name}\n}\n\nfunc (t *TradeExecutor) Name() string { return t.name }\n\nfunc (t *TradeExecutor) RegisterConfig(app modular.Application) {}\n\nfunc (t *TradeExecutor) Init(app modular.Application) error {\n\tt.logger = app.Logger()\n\treturn nil\n}\n\nfunc (t *TradeExecutor) Execute(ctx context.Context, order TradeOrder) (*TradeResult, error) {\n\tt.logger.Info(fmt.Sprintf(\"Executing %s order for %s: qty=%d price=%.2f\",\n\t\torder.Action, order.Symbol, order.Quantity, order.Price))\n\n\t// [DEMO STUB] Returns a simulated order confirmation.\n\t// In production, replace this with a real brokerage API call (e.g. Alpaca, TD Ameritrade).\n\treturn \u0026TradeResult{\n\t\tOrderID:   fmt.Sprintf(\"ORD-%d\", time.Now().UnixNano()),\n\t\tStatus:    \"executed\",\n\t\tAction:    order.Action,\n\t\tPrice:     order.Price,\n\t\tTimestamp: time.Now(),\n\t}, nil\n}\n\nvar _ modular.Module = (*TradeExecutor)(nil)\n`,\n\t\t},\n\t},\n}\n```\nStockTradingResponse is the expected generated response for the stock trading example. This serves as a reference for tests and documentation.\n\n","path":"github.com/GoCodeAlone/workflow/ai/examples","name":"examples","synopsis":"Package examples contains complete examples of AI-generated workflows.","isRedistributable":true}
