Skip to content

Commit

Permalink
Merge pull request #68 from krishkalaria12/main
Browse files Browse the repository at this point in the history
Fixed claude and perplexity errors for ai models
  • Loading branch information
webdevcody authored Oct 17, 2024
2 parents 2f25397 + 0ffcc7a commit 7a4d2ed
Show file tree
Hide file tree
Showing 5 changed files with 146 additions and 43 deletions.
2 changes: 2 additions & 0 deletions app/games/[gameId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export default function GamePage({ params }: { params: { gameId: string } }) {
gameId: params.gameId as Id<"games">,
});

console.log((results));

return (
<div className="container mx-auto max-w-5xl min-h-screen flex flex-col items-center py-12 pb-24 gap-8">
<h1>Game {params.gameId}</h1>
Expand Down
90 changes: 90 additions & 0 deletions convex/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Welcome to your Convex functions directory!

Write your Convex functions here.
See https://docs.convex.dev/functions for more.

A query function that takes two arguments looks like:

```ts
// functions.js
import { query } from "./_generated/server";
import { v } from "convex/values";

export const myQueryFunction = query({
// Validators for arguments.
args: {
first: v.number(),
second: v.string(),
},

// Function implementation.
handler: async (ctx, args) => {
// Read the database as many times as you need here.
// See https://docs.convex.dev/database/reading-data.
const documents = await ctx.db.query("tablename").collect();

// Arguments passed from the client are properties of the args object.
console.log(args.first, args.second);

// Write arbitrary JavaScript here: filter, aggregate, build derived data,
// remove non-public properties, or create new objects.
return documents;
},
});
```

Using this query function in a React component looks like:

```ts
const data = useQuery(api.functions.myQueryFunction, {
first: 10,
second: "hello",
});
```

A mutation function looks like:

```ts
// functions.js
import { mutation } from "./_generated/server";
import { v } from "convex/values";

export const myMutationFunction = mutation({
// Validators for arguments.
args: {
first: v.string(),
second: v.string(),
},

// Function implementation.
handler: async (ctx, args) => {
// Insert or modify documents in the database here.
// Mutations can also read from the database like queries.
// See https://docs.convex.dev/database/writing-data.
const message = { body: args.first, author: args.second };
const id = await ctx.db.insert("messages", message);

// Optionally, return a value from your mutation.
return await ctx.db.get(id);
},
});
```

Using this mutation function in a React component looks like:

```ts
const mutation = useMutation(api.functions.myMutationFunction);
function handleButtonPress() {
// fire and forget, the most common way to use mutations
mutation({ first: "Hello!", second: "me" });
// OR
// use the result once the mutation has completed
mutation({ first: "Hello!", second: "me" }).then((result) =>
console.log(result),
);
}
```

Use the Convex CLI to push your functions to a deployment. See everything
the Convex CLI can do by running `npx convex -h` in your project root
directory. To learn more, launch the docs with `npx convex docs`.
73 changes: 39 additions & 34 deletions models/claude-3-5-sonnet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,44 @@ export const claude35sonnet: ModelHandler = async (prompt, map) => {
apiKey: process.env.ANTHROPIC_API_KEY,
});

const response = await anthropic.messages.create({
model: "claude-3-sonnet-20240307",
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");
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 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,
};
};
23 changes: 15 additions & 8 deletions models/perplexity-llama.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from 'axios';
import { z } from 'zod';
import { ModelHandler } from './index';

Expand All @@ -18,7 +17,7 @@ const PerplexityResponseSchema = z.object({
delta: z.object({
role: z.string(),
content: z.string(),
}),
}).optional(),
})
),
usage: z.object({
Expand All @@ -42,8 +41,7 @@ export const perplexityModel: ModelHandler = async (prompt: string, map: string[

const messages = [
{ role: 'system', content: 'Be precise and concise.' },
{ role: 'user', content: prompt },
{ role: 'user', content: JSON.stringify(map) },
{ role: 'user', content: `${prompt}\n\nMap:\n${JSON.stringify(map)}` },
];

const data = {
Expand All @@ -63,14 +61,23 @@ export const perplexityModel: ModelHandler = async (prompt: string, map: string[
};

try {
const response = await axios.post('https://api.perplexity.ai/chat/completions', data, {
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 validatedResponse = PerplexityResponseSchema.parse(response.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)}`);
}

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);
Expand All @@ -82,6 +89,6 @@ export const perplexityModel: ModelHandler = async (prompt: string, map: string[
};
} catch (error) {
console.error('Failed to run Perplexity model Error:', error);
throw new Error('Failed to run Perplexity model');
throw error;
}
};
};
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"axios": "^1.7.7",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"convex": "^1.16.0",
Expand Down

0 comments on commit 7a4d2ed

Please sign in to comment.