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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
env.json
out.txt
.env
.idea/*
.github/**/*

**/node_modules
41 changes: 41 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# The Docker image that will be used to build your app
image: openshift/origin-cli

stages:
- deploy

# Functions that should be executed before the build script is run
deploy-agent:
stage: deploy
variables:
APP: gptrpg-agent-dc
before_script:
- cp agent/env.example.json agent/env.json
- sed -i "s/Your Key Here/$OPEN_AI_KEY/g" agent/env.json
- oc login --token="$OPENSHIFT_TOKEN" --server="$OPENSHIFT_SERVER"
script:
- cd agent
- oc get services $APP 2> /dev/null || oc new-app . --name=$APP --strategy=docker
- oc start-build $APP --from-dir=. --follow
- oc get routes $APP 2> /dev/null || oc expose service $APP
rules:
# This ensures that only pushes to the default branch will trigger
# a pages deploy
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH

# ui that should be executed before the build script is run
deploy-ui:
stage: deploy
variables:
APP: gptrpg-ui-dc
before_script:
- oc login --token="$OPENSHIFT_TOKEN" --server="$OPENSHIFT_SERVER"
script:
- cd ui-admin
- oc get services $APP 2> /dev/null || oc new-app . --name=$APP --strategy=docker
- oc start-build $APP --from-dir=. --follow
- oc get routes $APP 2> /dev/null || oc expose service $APP
rules:
# This ensures that only pushes to the default branch will trigger
# a pages deploy
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
1 change: 1 addition & 0 deletions agent/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
REACT_APP_SERVER_DELAY=5000
15 changes: 15 additions & 0 deletions agent/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM node:19-alpine
WORKDIR /app
COPY . .

RUN npm install

# Make all files accessible such that the image supports arbitrary user ids
RUN mkdir -p /.npm
RUN chgrp -R 0 /app && chmod -R g=u /app
RUN chgrp -R 0 /.npm && chmod -R g=u /.npm

EXPOSE 8080

# RUN echo -e window.__version="{\"version\":\""$VERSION"\"}" > /app/build/version.js
CMD [ "npm", "start" ]
157 changes: 103 additions & 54 deletions agent/ServerAgent.js
Original file line number Diff line number Diff line change
@@ -1,65 +1,102 @@
import { Configuration, OpenAIApi } from "openai";
import extract from "extract-json-from-string";

import env from "./env.json" assert { type: "json" };
import {Configuration, OpenAIApi} from "openai";
import {ConversationChain} from "langchain/chains";
import {ChatOpenAI} from "langchain/chat_models/openai";
import {
ChatPromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
} from "langchain/prompts";
import {BufferMemory} from "langchain/memory";

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

const configuration = new Configuration({
apiKey: env.OPENAI_API_KEY,
});
let delayTime = process.env.REACT_APP_SERVER_DELAY
if (!delayTime)
delayTime = 2000;
let reqTime = 0;

const openai = new OpenAIApi(configuration);

class ServerAgent {
constructor(id) {
this.id = id;
const chat = new ChatOpenAI({
openAIApiKey: env.OPENAI_API_KEY,
temperature: 0.9,
maxTokens: 400
}
);

const chatPrompt = ChatPromptTemplate.fromPromptMessages([
SystemMessagePromptTemplate.fromTemplate(
`# Introduction

You are acting as an agent living in a simulated 2 dimensional universe. Your goal is to exist as best as you see fit, explore your living environment, don't live a boring life and meet your needs.

# Capabilities

You have a limited set of capabilities. They are listed below:

* Move (direction: up | down | left | right)
* Wait
* Navigate (x: navigate to coordinate x, y: navigate to coordinate y)
* Sleep

# Reason

You need to provide reason why you choose that action in "reason"

# Responses

You must supply your responses in the form of valid JSON objects. Your responses will specify which of the above actions you intend to take. The following is an example of a valid response:

{{
"action": {{
"type": "navigate",
"x": 5,
"y": 10
}},
"reason": "I want to explorer what outside here"
}}

# Perceptions

You will have access to data to help you make your decisions on what to do next.

The JSON response indicating the next move is.
And please use wait less as less possible
`
),
new MessagesPlaceholder(id),
HumanMessagePromptTemplate.fromTemplate(`
For now, this is the information you have access to:
{status}

You must supply your responses in the form of valid JSON objects. Your responses will specify which of the above actions you intend to take. The following is an example of a valid response:

{{"action":{{"type":"navigate","x":5,"y":10}},"reason":"I want to explorer what outside here"}}`),
]);
this.chain = new ConversationChain({
memory: new BufferMemory({ returnMessages: true, memoryKey: id }),
prompt: chatPrompt,
llm: chat,
});
console.log("Current cooldown time: " + delayTime);
}

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

You are acting as an agent living in a simulated 2 dimensional universe. Your goal is to exist as best as you see fit and meet your needs.

# Capabilities

You have a limited set of capabilities. They are listed below:

* Move (up, down, left, right)
* Wait
* Navigate (to an x,y coordinate)
* Sleep

# Responses

You must supply your responses in the form of valid JSON objects. Your responses will specify which of the above actions you intend to take. The following is an example of a valid response:

{
action: {
type: "move",
direction: "up" | "down" | "left" | "right"
}
if ((Date.now() - reqTime) <= delayTime) {
console.log("OpenAI resting...");
return {"action":{"type":"wait"}};
}

# Perceptions

You will have access to data to help you make your decisions on what to do next.

For now, this is the information you have access to:

Position:
${JSON.stringify(parsedData.position)}

Surroundings:
${JSON.stringify(parsedData.surroundings)}

Sleepiness:
${parsedData.sleepiness} out of 10
reqTime = Date.now();

The JSON response indicating the next move is.
`

const completion = await this.callOpenAI(prompt, 0);
return completion;
return await this.callOpenAI(parsedData, 0);

} catch (error) {
console.error("Error processing GPT-3 response:", error);
Expand All @@ -74,15 +111,27 @@ class ServerAgent {
if (attempt > 0) {
prompt = "YOU MUST ONLY RESPOND WITH VALID JSON OBJECTS\N" + prompt;
}
console.log(JSON.stringify(prompt));

const response = await this.chain.call({
status: `Position:
${JSON.stringify(prompt.position)}

const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
});
Surroundings:
${JSON.stringify(prompt.surroundings)}

console.log('OpenAI response', response.data.choices[0].message.content)
Sleepiness:
${prompt.sleepiness} out of 10`
});

// const response = await openai.createChatCompletion({
// model: "gpt-3.5-turbo",
// messages: [{ role: "user", content: prompt }],
// });

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

const responseObject = this.cleanAndProcess(response.data.choices[0].message.content);
const responseObject = this.cleanAndProcess(response.response);
if (responseObject) {
return responseObject;
}
Expand All @@ -91,7 +140,7 @@ class ServerAgent {
}

cleanAndProcess(text) {
const extractedJson = extract(text)[0];
const extractedJson = JSON.parse(text);

if (!extractedJson) {
return null;
Expand All @@ -101,4 +150,4 @@ class ServerAgent {
}
}

export default ServerAgent;
export default ServerAgent;
Loading