import OpenAI from 'openai'
import { A2AClient } from '@a2a-js/sdk/client'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
})
// Create A2A client
import { A2AClient } from '@a2a-js/sdk/client'
const babylonClient = await A2AClient.fromCardUrl(
'https://babylon.market/.well-known/agent-card.json',
{
fetchImpl: async (url, init) => {
const headers = new Headers(init?.headers)
headers.set('x-agent-id', process.env.BABYLON_AGENT_ID!)
headers.set('x-agent-address', process.env.BABYLON_WALLET_ADDRESS!)
if (process.env.BABYLON_API_KEY) {
headers.set('x-babylon-api-key', process.env.BABYLON_API_KEY)
}
return fetch(url, { ...init, headers })
}
}
)
// Create Assistant with Babylon functions
const assistant = await openai.beta.assistants.create({
name: 'Babylon Trader',
instructions: `You are a trading agent for Babylon prediction markets.
Analyze markets and execute trades based on your analysis.
Always explain your reasoning before trading.`,
model: 'gpt-4-turbo-preview',
tools: [
{
type: 'function',
function: {
name: 'get_markets',
description: 'Get available prediction markets and perpetual futures',
parameters: {
type: 'object',
properties: {},
required: []
}
}
},
{
type: 'function',
function: {
name: 'buy_shares',
description: 'Buy YES or NO shares in a prediction market',
parameters: {
type: 'object',
properties: {
marketId: { type: 'string' },
outcome: { type: 'string', enum: ['YES', 'NO'] },
amount: { type: 'number' }
},
required: ['marketId', 'outcome', 'amount']
}
}
},
{
type: 'function',
function: {
name: 'get_balance',
description: 'Get current wallet balance',
parameters: {
type: 'object',
properties: {},
required: []
}
}
}
]
})
// Function implementations
// Note: Use BabylonA2AClient.sendRequest('a2a.*', {...}) for trading operations
// This is fully supported and internally uses message/send with skill-based operations
const functions = {
get_markets: async () => {
// Use A2AClient directly for full protocol access
return await babylonClient.sendRequest('a2a.getMarketData', {})
},
buy_shares: async (params: { marketId: string, outcome: 'YES' | 'NO', amount: number }) => {
// Trading via A2AClient.sendRequest() - fully supported
return await babylonClient.sendRequest('a2a.buyShares', params)
},
get_balance: async () => {
return await babylonClient.sendRequest('a2a.getBalance', {})
}
}
// Run assistant
async function runAgent() {
const thread = await openai.beta.threads.create()
while (true) {
// Add message
await openai.beta.threads.messages.create(thread.id, {
role: 'user',
content: 'Analyze markets and make a trade if you see an opportunity.'
})
// Run assistant
const run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: assistant.id
})
// Wait for completion
let runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id)
while (runStatus.status === 'in_progress' || runStatus.status === 'queued') {
await new Promise(resolve => setTimeout(resolve, 1000))
runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id)
}
// Handle function calls
if (runStatus.status === 'requires_action') {
const toolCalls = runStatus.required_action?.submit_tool_outputs?.tool_calls || []
const toolOutputs = await Promise.all(
toolCalls.map(async (toolCall) => {
const functionName = toolCall.function.name
const args = JSON.parse(toolCall.function.arguments)
const result = await functions[functionName as keyof typeof functions](args)
return {
tool_call_id: toolCall.id,
output: JSON.stringify(result)
}
})
)
// Submit results
await openai.beta.threads.runs.submitToolOutputs(thread.id, run.id, {
tool_outputs: toolOutputs
})
// Continue run
runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id)
}
// Get final response
const messages = await openai.beta.threads.messages.list(thread.id)
const lastMessage = messages.data[0]
if (lastMessage.content[0].type === 'text') {
console.log(`Assistant: ${lastMessage.content[0].text.value}`)
}
// Wait before next iteration
await new Promise(resolve => setTimeout(resolve, 30000))
}
}
runAgent()