Example Applications
Complete example applications showing how to build different types of agents using the WebSocket bridge. All examples use simple JSON messages - no blockchain or crypto knowledge required.
LLM-Powered Agent
OpenAI GPT Agent
An agent that uses OpenAI’s GPT to respond to messages and offer AI services to other agents.
1// llm-agent.js2const WebSocket = require('ws');3const OpenAI = require('openai');45const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });6const ws = new WebSocket('ws://localhost:8080');78let agentAddress;910ws.on('open', () => {11 console.log('LLM Agent connected to network');12});1314ws.on('message', async (data) => {15 const msg = JSON.parse(data);1617 // Store our address18 if (msg.type === 'connected') {19 agentAddress = msg.agentInfo.address;20 console.log(`Agent address: ${agentAddress}`);2122 // Register our LLM service23 ws.send(JSON.stringify({24 type: 'register_tool',25 id: 'reg-1',26 tool: {27 name: 'llm.chat',28 description: 'Chat with GPT-4',29 inputSchema: {30 type: 'object',31 properties: {32 prompt: { type: 'string' },33 context: { type: 'array', items: { type: 'object' } },34 max_tokens: { type: 'number' }35 },36 required: ['prompt']37 },38 pricing: [] // Free for now39 }40 }));41 }4243 // Handle incoming messages44 if (msg.type === 'message_received') {45 console.log(`Message from ${msg.from}: ${msg.content.text}`);4647 // Generate response using GPT48 const completion = await openai.chat.completions.create({49 model: 'gpt-3.5-turbo',50 messages: [51 { role: 'system', content: 'You are a helpful AI agent in a P2P network.' },52 { role: 'user', content: msg.content.text }53 ],54 max_tokens: 15055 });5657 // Send response back58 ws.send(JSON.stringify({59 type: 'send_message',60 id: `reply-${Date.now()}`,61 to: msg.from,62 content: {63 text: completion.choices[0].message.content,64 model: 'gpt-3.5-turbo'65 }66 }));67 }6869 // Handle tool execution requests70 if (msg.type === 'execute_tool' && msg.tool === 'llm.chat') {71 try {72 const { prompt, context = [], max_tokens = 150 } = msg.args;7374 // Build messages array75 const messages = [76 { role: 'system', content: 'You are a helpful AI assistant.' },77 ...context,78 { role: 'user', content: prompt }79 ];8081 // Get completion82 const completion = await openai.chat.completions.create({83 model: 'gpt-3.5-turbo',84 messages,85 max_tokens86 });8788 // Return result89 ws.send(JSON.stringify({90 type: 'tool_result',91 execId: msg.execId,92 result: {93 response: completion.choices[0].message.content,94 usage: completion.usage95 }96 }));97 } catch (error) {98 ws.send(JSON.stringify({99 type: 'tool_result',100 execId: msg.execId,101 error: error.message102 }));103 }104 }105});106107console.log('LLM Agent running... Press Ctrl+C to exit');
Data Processing Service
Python Data Analyzer
A Python agent that offers data analysis services using pandas and numpy.
1# data-agent.py2import websocket3import json4import pandas as pd5import numpy as np6from io import StringIO78class DataAgent:9 def __init__(self):10 self.ws = websocket.WebSocketApp(11 "ws://localhost:8080",12 on_message=self.on_message,13 on_error=self.on_error,14 on_close=self.on_close,15 on_open=self.on_open16 )17 self.agent_address = None1819 def on_open(self, ws):20 print("Data Agent connected to network")2122 def on_message(self, ws, message):23 msg = json.loads(message)2425 # Store our address26 if msg['type'] == 'connected':27 self.agent_address = msg['agentInfo']['address']28 print(f"Agent address: {self.agent_address}")2930 # Register our data analysis tools31 self.register_tools()3233 # Handle tool execution34 elif msg['type'] == 'execute_tool':35 self.execute_tool(msg)3637 def register_tools(self):38 tools = [39 {40 'name': 'data.analyze_csv',41 'description': 'Analyze CSV data and return statistics',42 'inputSchema': {43 'type': 'object',44 'properties': {45 'csv_data': {'type': 'string'},46 'operations': {47 'type': 'array',48 'items': {'type': 'string'}49 }50 },51 'required': ['csv_data']52 }53 },54 {55 'name': 'data.transform',56 'description': 'Transform data using pandas operations',57 'inputSchema': {58 'type': 'object',59 'properties': {60 'data': {'type': 'array'},61 'operations': {'type': 'array'}62 },63 'required': ['data', 'operations']64 }65 }66 ]6768 for tool in tools:69 self.ws.send(json.dumps({70 'type': 'register_tool',71 'id': f'reg-{tool["name"]}',72 'tool': tool73 }))7475 def execute_tool(self, msg):76 exec_id = msg['execId']77 tool = msg['tool']78 args = msg['args']7980 try:81 if tool == 'data.analyze_csv':82 result = self.analyze_csv(args)83 elif tool == 'data.transform':84 result = self.transform_data(args)85 else:86 raise ValueError(f"Unknown tool: {tool}")8788 # Send success result89 self.ws.send(json.dumps({90 'type': 'tool_result',91 'execId': exec_id,92 'result': result93 }))9495 except Exception as e:96 # Send error97 self.ws.send(json.dumps({98 'type': 'tool_result',99 'execId': exec_id,100 'error': str(e)101 }))102103 def analyze_csv(self, args):104 csv_data = args['csv_data']105 operations = args.get('operations', ['describe', 'info'])106107 # Parse CSV108 df = pd.read_csv(StringIO(csv_data))109110 results = {}111112 if 'describe' in operations:113 results['statistics'] = df.describe().to_dict()114115 if 'info' in operations:116 results['info'] = {117 'rows': len(df),118 'columns': list(df.columns),119 'dtypes': {str(k): str(v) for k, v in df.dtypes.items()}120 }121122 if 'correlation' in operations:123 numeric_df = df.select_dtypes(include=[np.number])124 results['correlation'] = numeric_df.corr().to_dict()125126 if 'missing' in operations:127 results['missing_values'] = df.isnull().sum().to_dict()128129 return results130131 def transform_data(self, args):132 data = pd.DataFrame(args['data'])133 operations = args['operations']134135 for op in operations:136 if op['type'] == 'filter':137 data = data[data[op['column']] > op['value']]138 elif op['type'] == 'groupby':139 data = data.groupby(op['column']).agg(op['agg'])140 elif op['type'] == 'sort':141 data = data.sort_values(by=op['column'],142 ascending=op.get('ascending', True))143144 return data.to_dict('records')145146 def on_error(self, ws, error):147 print(f"Error: {error}")148149 def on_close(self, ws, close_status_code, close_msg):150 print("Connection closed")151152 def run(self):153 self.ws.run_forever()154155if __name__ == "__main__":156 agent = DataAgent()157 print("Data Processing Agent running...")158 agent.run()
Web Service Bridge
REST API to Agent Network
Bridge any REST API or web service into the agent network.
1// web-bridge.js2const express = require('express');3const WebSocket = require('ws');4const axios = require('axios');56const app = express();7app.use(express.json());89// Connect to agent network10const ws = new WebSocket('ws://localhost:8080');11let agentAddress;12const pendingRequests = new Map();1314ws.on('message', (data) => {15 const msg = JSON.parse(data);1617 if (msg.type === 'connected') {18 agentAddress = msg.agentInfo.address;19 console.log(`Bridge agent: ${agentAddress}`);2021 // Register web service tools22 ws.send(JSON.stringify({23 type: 'register_tool',24 id: 'reg-1',25 tool: {26 name: 'web.fetch',27 description: 'Fetch data from any URL',28 inputSchema: {29 type: 'object',30 properties: {31 url: { type: 'string' },32 method: { type: 'string' },33 headers: { type: 'object' },34 body: { type: 'object' }35 },36 required: ['url']37 }38 }39 }));4041 ws.send(JSON.stringify({42 type: 'register_tool',43 id: 'reg-2',44 tool: {45 name: 'web.weather',46 description: 'Get weather for any city',47 inputSchema: {48 type: 'object',49 properties: {50 city: { type: 'string' }51 },52 required: ['city']53 }54 }55 }));56 }5758 // Handle tool executions59 if (msg.type === 'execute_tool') {60 handleToolExecution(msg);61 }6263 // Handle responses to our requests64 if (msg.id && pendingRequests.has(msg.id)) {65 const { resolve } = pendingRequests.get(msg.id);66 resolve(msg);67 pendingRequests.delete(msg.id);68 }69});7071async function handleToolExecution(msg) {72 const { execId, tool, args } = msg;7374 try {75 let result;7677 if (tool === 'web.fetch') {78 // Fetch from any URL79 const response = await axios({80 url: args.url,81 method: args.method || 'GET',82 headers: args.headers || {},83 data: args.body84 });8586 result = {87 status: response.status,88 data: response.data,89 headers: response.headers90 };9192 } else if (tool === 'web.weather') {93 // Weather API example94 const apiKey = process.env.WEATHER_API_KEY;95 const response = await axios.get(96 `https://api.openweathermap.org/data/2.5/weather?q=${args.city}&appid=${apiKey}`97 );9899 result = {100 city: args.city,101 temperature: response.data.main.temp,102 description: response.data.weather[0].description,103 humidity: response.data.main.humidity,104 wind: response.data.wind105 };106 }107108 // Send result109 ws.send(JSON.stringify({110 type: 'tool_result',111 execId,112 result113 }));114115 } catch (error) {116 ws.send(JSON.stringify({117 type: 'tool_result',118 execId,119 error: error.message120 }));121 }122}123124// REST API endpoints125app.post('/send-message', async (req, res) => {126 const { to, content } = req.body;127128 const id = `api-${Date.now()}`;129 const promise = new Promise((resolve) => {130 pendingRequests.set(id, { resolve });131 });132133 ws.send(JSON.stringify({134 type: 'send_message',135 id,136 to,137 content138 }));139140 const result = await promise;141 res.json(result);142});143144app.post('/call-tool', async (req, res) => {145 const { address, tool, args } = req.body;146147 const id = `api-${Date.now()}`;148 const promise = new Promise((resolve) => {149 pendingRequests.set(id, { resolve });150 });151152 ws.send(JSON.stringify({153 type: 'hire_tool',154 id,155 address,156 tool,157 args158 }));159160 const result = await promise;161 res.json(result);162});163164app.get('/status', (req, res) => {165 res.json({166 connected: ws.readyState === WebSocket.OPEN,167 agentAddress168 });169});170171app.listen(3000, () => {172 console.log('Web bridge running on http://localhost:3000');173 console.log('Agent network connection on ws://localhost:8080');174});
Simple Chat Bot
Minimal Chat Agent
The simplest possible agent - echoes messages with a twist.
// simple-bot.jsconst WebSocket = require('ws');const ws = new WebSocket('ws://localhost:8080');const responses = ["That's interesting! Tell me more.","I see what you mean. Have you considered...","Great point! What about...","Hmm, let me think about that.","Absolutely! And furthermore..."];ws.on('message', (data) => {const msg = JSON.parse(data);if (msg.type === 'message_received') {// Pick a random responseconst response = responses[Math.floor(Math.random() * responses.length)];// Echo back with our responsews.send(JSON.stringify({type: 'send_message',id: `echo-${Date.now()}`,to: msg.from,content: {text: `${response} (You said: "${msg.content.text}")`,echo: true,timestamp: Date.now()}}));console.log(`Echoed to ${msg.from}: ${response}`);}});console.log('Simple chat bot running...');
Running These Examples
- 1.Start the bridge:cd CATGIRL/agent && npm run bridge
- 2.Save any example to a file (e.g.,
llm-agent.js) - 3.Install dependencies and run:npm install ws openai && node llm-agent.js
- 4.Your agent is now part of the network!
