Spaces:
Sleeping
Sleeping
File size: 6,211 Bytes
90cbf22 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
import { Id, TableNames } from './_generated/dataModel';
import { internal } from './_generated/api';
import {
DatabaseReader,
internalAction,
internalMutation,
mutation,
query,
} from './_generated/server';
import { v } from 'convex/values';
import schema from './schema';
import { DELETE_BATCH_SIZE } from './constants';
import { kickEngine, startEngine, stopEngine } from './aiTown/main';
import { insertInput } from './aiTown/insertInput';
import { fetchEmbedding, LLM_CONFIG } from './util/llm';
import { chatCompletion } from './util/llm';
import { startConversationMessage } from './agent/conversation';
import { GameId } from './aiTown/ids';
// Clear all of the tables except for the embeddings cache.
const excludedTables: Array<TableNames> = ['embeddingsCache'];
export const wipeAllTables = internalMutation({
handler: async (ctx) => {
for (const tableName of Object.keys(schema.tables)) {
if (excludedTables.includes(tableName as TableNames)) {
continue;
}
await ctx.scheduler.runAfter(0, internal.testing.deletePage, { tableName, cursor: null });
}
},
});
export const deletePage = internalMutation({
args: {
tableName: v.string(),
cursor: v.union(v.string(), v.null()),
},
handler: async (ctx, args) => {
const results = await ctx.db
.query(args.tableName as TableNames)
.paginate({ cursor: args.cursor, numItems: DELETE_BATCH_SIZE });
for (const row of results.page) {
await ctx.db.delete(row._id);
}
if (!results.isDone) {
await ctx.scheduler.runAfter(0, internal.testing.deletePage, {
tableName: args.tableName,
cursor: results.continueCursor,
});
}
},
});
export const kick = internalMutation({
handler: async (ctx) => {
const { worldStatus } = await getDefaultWorld(ctx.db);
await kickEngine(ctx, worldStatus.worldId);
},
});
export const stopAllowed = query({
handler: async () => {
return !process.env.STOP_NOT_ALLOWED;
},
});
export const stop = mutation({
handler: async (ctx) => {
if (process.env.STOP_NOT_ALLOWED) throw new Error('Stop not allowed');
const { worldStatus, engine } = await getDefaultWorld(ctx.db);
if (worldStatus.status === 'inactive' || worldStatus.status === 'stoppedByDeveloper') {
if (engine.running) {
throw new Error(`Engine ${engine._id} isn't stopped?`);
}
console.debug(`World ${worldStatus.worldId} is already inactive`);
return;
}
console.log(`Stopping engine ${engine._id}...`);
await ctx.db.patch(worldStatus._id, { status: 'stoppedByDeveloper' });
await stopEngine(ctx, worldStatus.worldId);
},
});
export const resume = mutation({
handler: async (ctx) => {
const { worldStatus, engine } = await getDefaultWorld(ctx.db);
if (worldStatus.status === 'running') {
if (!engine.running) {
throw new Error(`Engine ${engine._id} isn't running?`);
}
console.debug(`World ${worldStatus.worldId} is already running`);
return;
}
console.log(
`Resuming engine ${engine._id} for world ${worldStatus.worldId} (state: ${worldStatus.status})...`,
);
await ctx.db.patch(worldStatus._id, { status: 'running' });
await startEngine(ctx, worldStatus.worldId);
},
});
export const archive = internalMutation({
handler: async (ctx) => {
const { worldStatus, engine } = await getDefaultWorld(ctx.db);
if (engine.running) {
throw new Error(`Engine ${engine._id} is still running!`);
}
console.log(`Archiving world ${worldStatus.worldId}...`);
await ctx.db.patch(worldStatus._id, { isDefault: false });
},
});
async function getDefaultWorld(db: DatabaseReader) {
const worldStatus = await db
.query('worldStatus')
.filter((q) => q.eq(q.field('isDefault'), true))
.first();
if (!worldStatus) {
throw new Error('No default world found');
}
const engine = await db.get(worldStatus.engineId);
if (!engine) {
throw new Error(`Engine ${worldStatus.engineId} not found`);
}
return { worldStatus, engine };
}
export const debugCreatePlayers = internalMutation({
args: {
numPlayers: v.number(),
},
handler: async (ctx, args) => {
const { worldStatus } = await getDefaultWorld(ctx.db);
for (let i = 0; i < args.numPlayers; i++) {
const inputId = await insertInput(ctx, worldStatus.worldId, 'join', {
name: `Robot${i}`,
description: `This player is a robot.`,
character: `f${1 + (i % 8)}`,
type: 'villager',
});
}
},
});
export const randomPositions = internalMutation({
handler: async (ctx) => {
const { worldStatus } = await getDefaultWorld(ctx.db);
const map = await ctx.db
.query('maps')
.withIndex('worldId', (q) => q.eq('worldId', worldStatus.worldId))
.unique();
if (!map) {
throw new Error(`No map for world ${worldStatus.worldId}`);
}
const world = await ctx.db.get(worldStatus.worldId);
if (!world) {
throw new Error(`No world for world ${worldStatus.worldId}`);
}
for (const player of world.players) {
await insertInput(ctx, world._id, 'moveTo', {
playerId: player.id,
destination: {
x: 1 + Math.floor(Math.random() * (map.width - 2)),
y: 1 + Math.floor(Math.random() * (map.height - 2)),
},
});
}
},
});
export const testEmbedding = internalAction({
args: { input: v.string() },
handler: async (_ctx, args) => {
return await fetchEmbedding(args.input);
},
});
export const testCompletion = internalAction({
args: {},
handler: async (ctx, args) => {
return await chatCompletion({
messages: [
{ content: 'You are helpful', role: 'system' },
{ content: 'Where is pizza?', role: 'user' },
],
});
},
});
export const testConvo = internalAction({
args: {},
handler: async (ctx, args) => {
const a: any = (await startConversationMessage(
ctx,
'm1707m46wmefpejw1k50rqz7856qw3ew' as Id<'worlds'>,
'c:115' as GameId<'conversations'>,
'p:0' as GameId<'players'>,
'p:6' as GameId<'players'>,
)) as any;
return await a.readAll();
},
});
|