Skip to content

Commit

Permalink
Refactor + readme
Browse files Browse the repository at this point in the history
  • Loading branch information
Grzegorz Tańczyk committed Jul 9, 2024
1 parent a292d5a commit 0bbe390
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 146 deletions.
33 changes: 6 additions & 27 deletions games/nukes/README.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,9 @@
# React + TypeScript + Vite
# Nukes

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
This is a simple React application that simulates a nuclear war game.

Currently, two official plugins are available:
To run the game locally:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## Expanding the ESLint configuration

If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:

- Configure the top-level `parserOptions` property like this:

```js
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
}
```

- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list
1. Install Node.js
2. Install dependencies: `npm i`
3. Run the development server: `npm run dev`
61 changes: 4 additions & 57 deletions games/nukes/codegen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,60 +26,7 @@ This will run the codegen script, which will:

The codegen script accepts the following options:

* `--dry-run`: Run the codegen script without updating the source code.
* `--consider-all-files`: Consider all files for code generation, even if they don't contain the `CODEGEN START` and `CODEGEN END` comments.
* `--allow-file-create`: Allow the codegen script to create new files.
* `--allow-file-delete`: Allow the codegen script to delete files.

## Examples

The following examples show how to use the codegen module to generate code for different parts of the application.

### Example 1: Generating a new function

```typescript
// CODEGEN START: Generate a function that calculates the distance between two points
// CODEGEN END
```

This will generate the following code:

```typescript
function calculateDistance(x1: number, y1: number, x2: number, y2: number): number {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
```

### Example 2: Generating a new component

```typescript
// CODEGEN START: Generate a React component that displays a list of items
// CODEGEN END
```

This will generate the following code:

```typescript
import React from 'react';

type Item = {
id: string;
name: string;
};

type ItemListProps = {
items: Item[];
};

const ItemList: React.FC<ItemListProps> = ({ items }) => {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};

export default ItemList;
```
- `--dry-run`: Run the codegen script without updating the source code.
- `--consider-all-files`: Consider all files for code generation, even if they don't contain the `CODEGEN START` and `CODEGEN END` comments.
- `--allow-file-create`: Allow the codegen script to create new files.
- `--allow-file-delete`: Allow the codegen script to delete files.
14 changes: 9 additions & 5 deletions games/nukes/codegen/find-files.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,26 @@ const __dirname = path.dirname(__filename);

const codegenDir = path.join(__dirname);
const srcDir = path.join(__dirname, '..', 'src');
const rootDir = path.join(__dirname, '..');

function findFiles(dir, ...exts) {
function findFiles(dir, recursive, ...exts) {
const files = [];
const items = fs.readdirSync(dir);
for (const item of items) {
const fullPath = path.join(dir, item);
if (fs.statSync(fullPath).isDirectory()) {
files.push(...findFiles(fullPath, ...exts));
if (recursive) {
files.push(...findFiles(fullPath, ...exts));
}
} else if (exts.includes(path.extname(fullPath))) {
files.push(fullPath);
}
}
return files;
}

const jsFiles = findFiles(codegenDir, '.js', '.md');
const tsFiles = findFiles(srcDir, '.ts', '.tsx', '.md');
const rootFiles = findFiles(rootDir, false, '.md');
const codegenFiles = findFiles(codegenDir, true, '.js', '.md');
const gameFiles = findFiles(srcDir, true, '.ts', '.tsx', '.md');

export const sourceFiles = [...jsFiles, ...tsFiles];
export const sourceFiles = [...rootFiles, ...codegenFiles, ...gameFiles];
58 changes: 2 additions & 56 deletions games/nukes/codegen/index.js
Original file line number Diff line number Diff line change
@@ -1,64 +1,10 @@
import { VertexAI } from '@google-cloud/vertexai';
import { systemPrompt, codeGenPrompt } from './prompt-gen.js';
import { parsePromptResponse } from './prompt-parse.js';
import { updateFiles } from './update-files.js';

// Initialize Vertex with your Cloud project and location
const vertex_ai = new VertexAI({ project: 'gamedevpl', location: 'us-central1' });
const model = 'gemini-1.5-pro-001';

// Instantiate the models
const generativeModel = vertex_ai.preview.getGenerativeModel({
model: model,
generationConfig: {
maxOutputTokens: 8192,
temperature: 1,
topP: 0.95,
},
safetySettings: [
{
category: 'HARM_CATEGORY_HATE_SPEECH',
threshold: 'BLOCK_ONLY_HIGH',
},
{
category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
threshold: 'BLOCK_ONLY_HIGH',
},
{
category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
threshold: 'BLOCK_ONLY_HIGH',
},
{
category: 'HARM_CATEGORY_HARASSMENT',
threshold: 'BLOCK_ONLY_HIGH',
},
],
systemInstruction: {
role: 'system',
parts: [
{
text: systemPrompt,
},
],
},
});

const text1 = {
text: codeGenPrompt,
};

async function generateContent() {
const req = {
contents: [{ role: 'user', parts: [text1] }],
};

const result = await generativeModel.generateContent(req);

return result.response.candidates[0].content.parts[0].text;
}
import { generateContent } from './vertex-ai.js';

console.log('Generating response');
const promptResponseText = await generateContent();
const promptResponseText = await generateContent(systemPrompt, codeGenPrompt);
console.log('Parse response');
const parsedResponse = parsePromptResponse(promptResponseText);

Expand Down
1 change: 0 additions & 1 deletion games/nukes/codegen/prompt-gen.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import assert from 'node:assert';
import { sourceCode } from './read-files.js';
import { CODEGEN_END, CODEGEN_START } from './prompt-consts.js';

// read --dry-run flag from command line
const considerAllFiles = process.argv.includes('--consider-all-files');
const allowFileCreate = process.argv.includes('--allow-file-create');
const allowFileDelete = process.argv.includes('--allow-file-delete');
Expand Down
64 changes: 64 additions & 0 deletions games/nukes/codegen/vertex-ai.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { VertexAI } from '@google-cloud/vertexai';

// A function to generate content using the generative model
export async function generateContent(systemPrompt, prompt) {
const req = {
contents: [
{
role: 'user',
parts: [
{
text: prompt,
},
],
},
],
};

const result = await getGenModel(systemPrompt).generateContent(req);

return result.response.candidates[0].content.parts[0].text;
}

// A function to get the generative model
export function getGenModel(systemPrompt) {
// Initialize Vertex with your Cloud project and location
const vertex_ai = new VertexAI({ project: 'gamedevpl', location: 'us-central1' });
const model = 'gemini-1.5-pro-001';

// Instantiate the models
return vertex_ai.preview.getGenerativeModel({
model: model,
generationConfig: {
maxOutputTokens: 8192,
temperature: 1,
topP: 0.95,
},
safetySettings: [
{
category: 'HARM_CATEGORY_HATE_SPEECH',
threshold: 'BLOCK_ONLY_HIGH',
},
{
category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
threshold: 'BLOCK_ONLY_HIGH',
},
{
category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
threshold: 'BLOCK_ONLY_HIGH',
},
{
category: 'HARM_CATEGORY_HARASSMENT',
threshold: 'BLOCK_ONLY_HIGH',
},
],
systemInstruction: {
role: 'system',
parts: [
{
text: systemPrompt,
},
],
},
});
}

0 comments on commit 0bbe390

Please sign in to comment.