Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 34 additions & 7 deletions agent/ServerAgent.js → agent/ServerAgent.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
import { Configuration, OpenAIApi } from "openai";
import extract from "extract-json-from-string";

import env from "./env.json" assert { type: "json" };
import env from "./env.json";

interface ParsedData {
agent_id: string;
position: {
x: number;
y: number;
}
surroundings: any;
sleepiness: number;
}

interface ActionResponse {
action: {
type: "move" | "wait",
direction?: "up" | "down" | "left" | "right"
}
}

const configuration = new Configuration({
apiKey: env.OPENAI_API_KEY,
Expand All @@ -10,11 +27,13 @@ const configuration = new Configuration({
const openai = new OpenAIApi(configuration);

class ServerAgent {
constructor(id) {
id: string;

constructor(id: string) {
this.id = id;
}

async processMessage(parsedData) {
async processMessage(parsedData: ParsedData) {
try {
const prompt = `# Introduction

Expand Down Expand Up @@ -66,7 +85,7 @@ class ServerAgent {
}
}

async callOpenAI(prompt, attempt) {
async callOpenAI(prompt: string, attempt: number): Promise<ActionResponse | null> {
if (attempt > 3) {
return null;
}
Expand All @@ -80,17 +99,25 @@ class ServerAgent {
messages: [{ role: "user", content: prompt }],
});

console.log('OpenAI response', response.data.choices[0].message.content)
const message = response.data.choices[0].message

if (!message) {
console.error('Message is undefined, response: ', response)

return null
}

console.log('OpenAI response', message.content)

const responseObject = this.cleanAndProcess(response.data.choices[0].message.content);
const responseObject = this.cleanAndProcess(message.content);
if (responseObject) {
return responseObject;
}

return await this.callOpenAI(prompt, attempt + 1);
}

cleanAndProcess(text) {
cleanAndProcess(text: string) {
const extractedJson = extract(text)[0];

if (!extractedJson) {
Expand Down
1 change: 1 addition & 0 deletions agent/extract-json-from-string.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'extract-json-from-string';
17 changes: 14 additions & 3 deletions agent/index.js → agent/index.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
import { WebSocketServer } from 'ws';
import ServerAgent from './ServerAgent.js';
import ServerAgent from './ServerAgent';

const wss = new WebSocketServer({ port: 8080 });

const agents = {};
const agents: {
[id: string]: ServerAgent
} = {};

wss.on('connection', function connection(ws) {
ws.on('error', console.error);

ws.on('message', async function message(data) {
const parsedData = JSON.parse(data);
const parsedData = JSON.parse(data.toString());

if (parsedData.type === 'create_agent') {
console.log(`Creating Agent: ${parsedData.agent_id}`);

const newAgentId = parsedData.agent_id;

if(agents[newAgentId]) {
ws.send(JSON.stringify({ type: 'agent_created', success: false, message: `Agent with id ${newAgentId} already exists` }));

return;
}

agents[newAgentId] = new ServerAgent(newAgentId);

ws.send(JSON.stringify({ type: 'agent_created', success: true, agent_id: newAgentId, message: `Agent with id ${newAgentId} created` }));
} else if (parsedData.type === 'requestNextMove') {
const agentId = parsedData.agent_id;

console.log(`requestNextMove message for agent: ${agentId}`);

if (agents[agentId]) {
const completion = await agents[agentId].processMessage(parsedData);

ws.send(JSON.stringify({ type: 'nextMove', agent_id: agentId, data: completion }));
} else {
ws.send(JSON.stringify({ type: 'error', message: `Agent with id ${agentId} not found` }));
Expand Down
3 changes: 1 addition & 2 deletions agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon index.js",
"start": "nodemon ./index.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"author": "",
"license": "ISC",
"dependencies": {
Expand Down
17 changes: 17 additions & 0 deletions agent/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
},
"include": [
"./**/*"
]
}
Loading