From 266f7fa46a859291131fddf23adfbcefc14412b4 Mon Sep 17 00:00:00 2001 From: Aaron Delasy Date: Thu, 17 Oct 2024 20:52:40 +0300 Subject: [PATCH] Code style fixes --- .github/workflows/convex.yml | 2 +- app/games/[gameId]/page.tsx | 2 - app/globals.css | 2 +- app/maps/page.tsx | 4 - app/play/[level]/page.tsx | 2 +- components/MapTester.tsx | 74 ---------------- components/ThemeToggle.tsx | 11 +-- convex/constants.ts | 6 +- convex/flags.ts | 2 +- convex/maps.ts | 1 - models/claude-3-5-sonnet.ts | 80 ++++++++--------- models/perplexity-llama.ts | 91 ++++++++++---------- simulators/zombie-survival/lib/pathfinder.ts | 9 +- tailwind.config.ts | 2 +- 14 files changed, 93 insertions(+), 195 deletions(-) delete mode 100644 components/MapTester.tsx diff --git a/.github/workflows/convex.yml b/.github/workflows/convex.yml index 1fc9dc8..2a620bb 100644 --- a/.github/workflows/convex.yml +++ b/.github/workflows/convex.yml @@ -18,4 +18,4 @@ jobs: - name: Deploy Convex 🚀 env: CONVEX_DEPLOY_KEY: ${{ secrets.CONVEX_DEPLOY_KEY }} - run: npx convex deploy \ No newline at end of file + run: npx convex deploy diff --git a/app/games/[gameId]/page.tsx b/app/games/[gameId]/page.tsx index 78a5872..5045d85 100644 --- a/app/games/[gameId]/page.tsx +++ b/app/games/[gameId]/page.tsx @@ -13,8 +13,6 @@ export default function GamePage({ params }: { params: { gameId: string } }) { gameId: params.gameId as Id<"games">, }); - console.log((results)); - return (

Game {params.gameId}

diff --git a/app/globals.css b/app/globals.css index c5a40ec..0ab80ec 100644 --- a/app/globals.css +++ b/app/globals.css @@ -60,7 +60,7 @@ --chart-4: 43 74% 66%; --chart-5: 27 87% 67%; } - + .dark { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; diff --git a/app/maps/page.tsx b/app/maps/page.tsx index 89d01df..281b99f 100644 --- a/app/maps/page.tsx +++ b/app/maps/page.tsx @@ -33,15 +33,11 @@ export default function AddMapPage() { map.forEach((row, y) => { row.forEach((cell, x) => { if (map[y][x] == " ") { - console.log("All well!"); flag = true; } }); }); - console.log(map); if (!flag) { - console.log("All set"); - console.log(map); alert("No place left to place the player!"); } else { createMap({ grid: map }); diff --git a/app/play/[level]/page.tsx b/app/play/[level]/page.tsx index 8d57c47..2820d1d 100644 --- a/app/play/[level]/page.tsx +++ b/app/play/[level]/page.tsx @@ -1,7 +1,7 @@ "use client"; import { useEffect, useState } from "react"; -import { useMutation, useQuery, useAction, Authenticated } from "convex/react"; +import { useMutation, useQuery, Authenticated } from "convex/react"; import { api } from "@/convex/_generated/api"; import { Button } from "@/components/ui/button"; import { Visualizer } from "../../visualizer"; diff --git a/components/MapTester.tsx b/components/MapTester.tsx deleted file mode 100644 index b22a99c..0000000 --- a/components/MapTester.tsx +++ /dev/null @@ -1,74 +0,0 @@ -"use client"; - -// import { Map } from "@/app/map"; -// import { api } from "@/convex/_generated/api"; -// import { useAction } from "convex/react"; -// import React, { useState } from "react"; -// import { Button } from "./ui/button"; -// import { -// Select, -// SelectContent, -// SelectItem, -// SelectTrigger, -// SelectValue, -// } from "./ui/select"; -// import { AI_MODELS } from "@/convex/constants"; -// import { Id } from "@/convex/_generated/dataModel"; - -const MapTester = ({ map }: { map: string[][] }) => { - return null; - - // const getPlayerMap = useAction(api.openai.playMapAction); - // const [resMap, setResMap] = useState(); - // const [loading, setLoading] = useState(false); - // const [model, setModel] = useState(AI_MODELS[0].model); - - // const handleClick = async () => { - // setLoading(true); - // try { - // const res = await getPlayerMap({ - // level: 1, - // mapId: "zombiemap", - // map, - // modelId: model, - // gameId: "zombiegame" as Id<"games">, - // }); - - // // type safe resulting object - // console.log(res); - // setResMap(res?.map); - // } catch (error) { - // console.error(error); - // } finally { - // setLoading(false); - // } - // }; - - // return ( - // <> - //
- // - // - //
- //
- // {loading &&

Loading result map...

} - // {resMap && } - //
- // - // ); -}; - -export default MapTester; diff --git a/components/ThemeToggle.tsx b/components/ThemeToggle.tsx index c762266..6fda358 100644 --- a/components/ThemeToggle.tsx +++ b/components/ThemeToggle.tsx @@ -2,7 +2,6 @@ import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { DesktopIcon, MoonIcon, SunIcon } from "@radix-ui/react-icons"; -import { useState, useEffect } from "react"; import { useTheme } from "next-themes"; export function ThemeToggle() { @@ -14,14 +13,10 @@ export function ThemeToggle() { type="single" size="sm" value={theme} - onValueChange={(e) => { - console.log(`theme: ${theme}`); - console.log(`darkMode: ${darkMode}`); - setTheme(e); - }} - className={`${"flex px-1 py-1 rounded-md"} ${theme == "light" || (theme=="system" && darkMode=="light") ? "bg-blue-200" : "bg-slate-700"}`} + onValueChange={(e) => setTheme(e)} + className={`${"flex px-1 py-1 rounded-md"} ${theme == "light" || (theme == "system" && darkMode == "light") ? "bg-blue-200" : "bg-slate-700"}`} > - {theme == "light" || (theme=="system"&& darkMode=="light") ? ( + {theme == "light" || (theme == "system" && darkMode == "light") ? ( diff --git a/convex/constants.ts b/convex/constants.ts index 0d6ba7a..4499318 100644 --- a/convex/constants.ts +++ b/convex/constants.ts @@ -9,12 +9,12 @@ export const AI_MODELS = [ }, { model: "claude-3.5-sonnet", - name: "Claude 3.5 Sonnnet" + name: "Claude 3.5 Sonnnet", }, { model: "perplexity-llama-3.1", - name: "Perplextity AI" - } + name: "Perplextity AI", + }, ]; export const AI_MODEL_IDS = AI_MODELS.map((model) => model.model); diff --git a/convex/flags.ts b/convex/flags.ts index 24538e6..2addc37 100644 --- a/convex/flags.ts +++ b/convex/flags.ts @@ -2,7 +2,7 @@ import { query } from "./_generated/server"; export const getFlags = query({ args: {}, - handler: async (ctx) => { + handler: async () => { return { showTestPage: process.env.FLAG_TEST_PAGE === "true", enableCronJobs: process.env.FLAG_CRON_JOBS === "true", diff --git a/convex/maps.ts b/convex/maps.ts index b90d37e..b1283ac 100644 --- a/convex/maps.ts +++ b/convex/maps.ts @@ -9,7 +9,6 @@ import { v } from "convex/values"; import { ZombieSurvival } from "../simulators/zombie-survival"; import { api, internal } from "./_generated/api"; import { runModel } from "../models"; -import { auth } from "./auth"; import { getAuthUserId } from "@convex-dev/auth/server"; const LEVELS = [ diff --git a/models/claude-3-5-sonnet.ts b/models/claude-3-5-sonnet.ts index c51f1fd..7f2b124 100644 --- a/models/claude-3-5-sonnet.ts +++ b/models/claude-3-5-sonnet.ts @@ -2,48 +2,42 @@ import { Anthropic } from "@anthropic-ai/sdk"; import { type ModelHandler } from "."; export const claude35sonnet: ModelHandler = async (prompt, map) => { - const anthropic = new Anthropic({ - apiKey: process.env.ANTHROPIC_API_KEY, - }); + const anthropic = new Anthropic({ + apiKey: process.env.ANTHROPIC_API_KEY, + }); - try { - const response = await anthropic.messages.create({ - model: "claude-3-5-sonnet-20240620", - max_tokens: 1024, - temperature: 0, - system: prompt, - messages: [ - { - role: "user", - content: JSON.stringify(map), - }, - ], - }); - - const content = response.content[0]; - - if (content.type !== "text") { - throw new Error("Unexpected response type from Claude"); - } - - const parsedResponse = JSON.parse(content.text); - - // Validate the response structure - if ( - !Array.isArray(parsedResponse.boxCoordinates) || - !Array.isArray(parsedResponse.playerCoordinates) || - typeof parsedResponse.reasoning !== "string" - ) { - throw new Error("Invalid response structure"); - } - - return { - boxCoordinates: parsedResponse.boxCoordinates, - playerCoordinates: parsedResponse.playerCoordinates, - reasoning: parsedResponse.reasoning, - }; - } catch (error) { - console.error("Error in claude35sonnet:", error); - throw error; - } + const response = await anthropic.messages.create({ + model: "claude-3-5-sonnet-20240620", + max_tokens: 1024, + temperature: 0, + system: prompt, + messages: [ + { + role: "user", + content: JSON.stringify(map), + }, + ], + }); + + const content = response.content[0]; + + if (content.type !== "text") { + throw new Error("Unexpected response type from Claude"); + } + + const parsedResponse = JSON.parse(content.text); + + if ( + !Array.isArray(parsedResponse.boxCoordinates) || + !Array.isArray(parsedResponse.playerCoordinates) || + typeof parsedResponse.reasoning !== "string" + ) { + throw new Error("Invalid response structure"); + } + + return { + boxCoordinates: parsedResponse.boxCoordinates, + playerCoordinates: parsedResponse.playerCoordinates, + reasoning: parsedResponse.reasoning, + }; }; diff --git a/models/perplexity-llama.ts b/models/perplexity-llama.ts index 7bf5e82..5153e34 100644 --- a/models/perplexity-llama.ts +++ b/models/perplexity-llama.ts @@ -1,5 +1,5 @@ -import { z } from 'zod'; -import { ModelHandler } from './index'; +import { z } from "zod"; +import { ModelHandler } from "./index"; const PerplexityResponseSchema = z.object({ id: z.string(), @@ -14,11 +14,13 @@ const PerplexityResponseSchema = z.object({ role: z.string(), content: z.string(), }), - delta: z.object({ - role: z.string(), - content: z.string(), - }).optional(), - }) + delta: z + .object({ + role: z.string(), + content: z.string(), + }) + .optional(), + }), ), usage: z.object({ prompt_tokens: z.number(), @@ -33,62 +35,57 @@ const GameResponseSchema = z.object({ boxCoordinates: z.array(z.array(z.number())), }); -export const perplexityModel: ModelHandler = async (prompt: string, map: string[][]) => { - const apiKey = process.env.PERPLEXITY_API_KEY; - if (!apiKey) { - throw new Error('PERPLEXITY_API_KEY is not set in the environment variables'); - } - +export const perplexityModel: ModelHandler = async ( + prompt: string, + map: string[][], +) => { const messages = [ - { role: 'system', content: 'Be precise and concise.' }, - { role: 'user', content: `${prompt}\n\nMap:\n${JSON.stringify(map)}` }, + { role: "system", content: "Be precise and concise." }, + { role: "user", content: `${prompt}\n\nMap:\n${JSON.stringify(map)}` }, ]; const data = { - model: 'llama-3.1-sonar-large-128k-online', + model: "llama-3.1-sonar-large-128k-online", messages, temperature: 0.2, top_p: 0.9, return_citations: true, - search_domain_filter: ['perplexity.ai'], + search_domain_filter: ["perplexity.ai"], return_images: false, return_related_questions: false, - search_recency_filter: 'month', + search_recency_filter: "month", top_k: 0, stream: false, presence_penalty: 0, frequency_penalty: 1, }; - try { - const response = await fetch('https://api.perplexity.ai/chat/completions', { - method: 'POST', - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json', - }, - body: JSON.stringify(data), - }); + const response = await fetch("https://api.perplexity.ai/chat/completions", { + method: "POST", + headers: { + Authorization: `Bearer ${process.env.PERPLEXITY_API_KEY}`, + "Content-Type": "application/json", + }, + body: JSON.stringify(data), + }); - if (!response.ok) { - const errorData = await response.json(); - console.error('API Error:', errorData); - throw new Error(`HTTP error! status: ${response.status}, message: ${JSON.stringify(errorData)}`); - } + if (!response.ok) { + const errorData = await response.json(); - const responseData = await response.json(); - const validatedResponse = PerplexityResponseSchema.parse(responseData); - const content = validatedResponse.choices[0].message.content; - const parsedContent = JSON.parse(content); - const gameResponse = GameResponseSchema.parse(parsedContent); - - return { - boxCoordinates: gameResponse.boxCoordinates, - playerCoordinates: gameResponse.playerCoordinates, - reasoning: gameResponse.reasoning, - }; - } catch (error) { - console.error('Failed to run Perplexity model Error:', error); - throw error; + throw new Error( + `HTTP error! status: ${response.status}, message: ${JSON.stringify(errorData)}`, + ); } -}; \ No newline at end of file + + const responseData = await response.json(); + const validatedResponse = PerplexityResponseSchema.parse(responseData); + const content = validatedResponse.choices[0].message.content; + const parsedContent = JSON.parse(content); + const gameResponse = GameResponseSchema.parse(parsedContent); + + return { + boxCoordinates: gameResponse.boxCoordinates, + playerCoordinates: gameResponse.playerCoordinates, + reasoning: gameResponse.reasoning, + }; +}; diff --git a/simulators/zombie-survival/lib/pathfinder.ts b/simulators/zombie-survival/lib/pathfinder.ts index fd9a031..f4acfeb 100644 --- a/simulators/zombie-survival/lib/pathfinder.ts +++ b/simulators/zombie-survival/lib/pathfinder.ts @@ -1,11 +1,4 @@ -import { - allDirections, - Direction, - directionFromString, - directionToString, - move, -} from "../Direction"; -import { EntityType } from "../entities/Entity"; +import { allDirections, Direction, move } from "../Direction"; import { Zombie } from "../entities/Zombie"; import { ZombieSurvival } from "../ZombieSurvival"; import { entityAt } from "./entityAt"; diff --git a/tailwind.config.ts b/tailwind.config.ts index 0248b43..8eaaee2 100644 --- a/tailwind.config.ts +++ b/tailwind.config.ts @@ -109,4 +109,4 @@ const config: Config = { }, }; -export default config; \ No newline at end of file +export default config;