# Lua-Hyperbeam API Integration Guide
This guide demonstrates how to make API calls from Lua using relay mechanisms and autonomous agent patterns. It covers two main approaches: external API integration and autonomous agent deployment.
## Core Concepts
### Relay Mechanism
The relay mechanism allows Lua processes to make HTTP requests to external APIs by sending messages through a relay service. This pattern enables secure and efficient API communication.
### Handler Pattern
Handlers process incoming messages and trigger specific actions. They follow a publish-subscribe pattern where messages are routed based on action types.
## 1. External API Integration
### Basic Configuration
Set up your API endpoint and configuration:
```lua
GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=GEMINI_API_KEY"
```
> **Note**: API keys are public when deployed on the AO network. Use free-tier services or implement proper key management.
### Request Handler
Create a handler to send requests to external APIs:
```lua
Handlers.add('Send-Prompt', 'Send-Prompt', function(msg)
assert(msg['user-prompt'], 'No user prompt provided')
print('\nProcessing user prompt...')
print('\nUser prompt:\n', msg['user-prompt'])
local promptBody = {
contents = {{
parts = {{
text = msg['user-prompt']
}}
}}
}
send({
target = id,
['relay-path'] = GEMINI_API_URL,
['relay-method'] = 'POST',
['relay-body'] = require('json').encode(promptBody),
['Content-Type'] = 'application/json',
resolve = '~relay@1.0/call/~patch@1.0',
action = 'Receive-Response'
})
end)
```
### Response Handler
Process responses from external APIs:
```lua
Handlers.add('Receive-Response', 'Receive-Response', function(msg)
if msg.body then
local response = require('json').decode(msg.body)
print('\nResponse:\n', response.candidates[1].content.parts[1].text)
print('\nResponse source:', msg['relay-path'])
else
print('Error or empty response:', msg)
end
end)
```
### Usage
1. Initialize the AOS process:
```bash
aos gemini_agent --url https://hb.arweave.asia
```
2. Load your Lua file:
```bash
.load gemini.lua
```
3. Send a request:
```lua
send({target=id, action='Send-Prompt', ['user-prompt']='hello from permaweb'})
```
## 2. Autonomous Agent Deployment
### Environment Setup
Install AOS (requires NodeJS):
```bash
npm install -g https://preview_ao.arweave.net
```
### Process Initialization
Spawn a new process on the network:
```bash
aos my_agent --url https://workshop.forward.computer
```
### State Management
Initialize persistent state variables:
```lua
Prices = Prices or {}
Portfolio = Portfolio or { cash = 10000, holdings = 0 }
```
### Data Fetching
Create handlers to fetch external data:
```lua
Handlers.add('Fetch-Price', 'Fetch-Price', function()
send({
target = id,
['relay-path'] = 'https://mockapi.com/price',
['relay-method'] = 'GET',
action = 'Process-Price'
})
end)
```
### Data Processing
Process incoming data and update state:
```lua
Handlers.add('Process-Price', 'Process-Price', function(msg)
if msg.body then
local priceData = require('json').decode(msg.body)
table.insert(Prices, priceData.price)
-- Maintain rolling window
if #Prices > 20 then
table.remove(Prices, 1)
end
send({ target = id, action = 'Evaluate-Strategy' })
else
print('Error fetching price data:', msg)
end
end)
```
### Strategy Implementation
Implement decision-making logic:
```lua
Handlers.add('Evaluate-Strategy', 'Evaluate-Strategy', function()
if #Prices < 20 then return end
-- Calculate Simple Moving Average
local sum = 0
for _, price in ipairs(Prices) do
sum = sum + price
end
local sma = sum / #Prices
local currentPrice = Prices[#Prices]
-- Execute strategy
if currentPrice < sma * 0.95 and Portfolio.cash >= currentPrice then
Portfolio.holdings = Portfolio.holdings + 1
Portfolio.cash = Portfolio.cash - currentPrice
print('Bought at', currentPrice)
elseif currentPrice > sma * 1.05 and Portfolio.holdings > 0 then
Portfolio.holdings = Portfolio.holdings - 1
Portfolio.cash = Portfolio.cash + currentPrice
print('Sold at', currentPrice)
end
end)
```
### Automation
Schedule periodic execution:
```lua
Timers.add('Price-Fetch-Timer', 60, 'Fetch-Price')
```
### Agent Activation
Start the autonomous agent:
```lua
send({ target = id, action = 'Fetch-Price' })
```
## Key Patterns
### 1. Message Flow
- Send requests using `send()` with relay parameters
- Process responses in dedicated handlers
- Chain handlers for complex workflows
### 2. Error Handling
- Always check for message body existence
- Implement fallback logic for failed requests
- Log errors for debugging
### 3. State Persistence
- Use `or` operator for state initialization
- Maintain data structures across handler calls
- Implement data cleanup for memory management
### 4. Relay Configuration
- Set `relay-path` for the target URL
- Specify `relay-method` (GET, POST, etc.)
- Include `relay-body` for POST requests
- Add necessary headers like `Content-Type`
## Best Practices
1. **Security**: Be mindful of public API keys in deployed processes
2. **Error Handling**: Always validate message content before processing
3. **State Management**: Initialize state variables with default values
4. **Resource Management**: Implement data cleanup for long-running processes
5. **Timing**: Use appropriate intervals for scheduled operations
This guide provides the foundation for building API-integrated Lua applications on the AO network, from simple external API calls to complex autonomous agents.