diff --git a/samples/js-firebase/.firebaserc b/samples/js-firebase/.firebaserc new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/samples/js-firebase/.firebaserc @@ -0,0 +1 @@ +{} diff --git a/samples/js-firebase/.gitignore b/samples/js-firebase/.gitignore new file mode 100644 index 0000000000..dbb58ffbfa --- /dev/null +++ b/samples/js-firebase/.gitignore @@ -0,0 +1,66 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +firebase-debug.log* +firebase-debug.*.log* + +# Firebase cache +.firebase/ + +# Firebase config + +# Uncomment this if you'd like others to create their own Firebase project. +# For a team working on the same Firebase project(s), it is recommended to leave +# it commented so all members can deploy to the same project(s) in .firebaserc. +# .firebaserc + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env diff --git a/samples/js-firebase/README.md b/samples/js-firebase/README.md new file mode 100644 index 0000000000..1231ce451c --- /dev/null +++ b/samples/js-firebase/README.md @@ -0,0 +1,17 @@ +# Angular and Genkit streaming sample + +This is a simple UI for streaming RPG character generator. + +To build: + +```bash +npm run build +``` + +Run: + +```bash +npm run start -- --project YOUR_PROJECT_ID +``` + +Point your browser to http://127.0.0.1:5000 diff --git a/samples/js-firebase/firebase.json b/samples/js-firebase/firebase.json new file mode 100644 index 0000000000..b0f342dc83 --- /dev/null +++ b/samples/js-firebase/firebase.json @@ -0,0 +1,19 @@ +{ + "functions": [ + { + "source": "functions", + "codebase": "default", + "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"] + } + ], + "hosting": { + "public": "my-app/dist/my-app/browser", + "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ] + } +} diff --git a/samples/js-firebase/functions/.gitignore b/samples/js-firebase/functions/.gitignore new file mode 100644 index 0000000000..9be0f014f4 --- /dev/null +++ b/samples/js-firebase/functions/.gitignore @@ -0,0 +1,10 @@ +# Compiled JavaScript files +lib/**/*.js +lib/**/*.js.map + +# TypeScript v1 declaration files +typings/ + +# Node.js dependency directory +node_modules/ +*.local \ No newline at end of file diff --git a/samples/js-firebase/functions/package.json b/samples/js-firebase/functions/package.json new file mode 100644 index 0000000000..4a35e29d79 --- /dev/null +++ b/samples/js-firebase/functions/package.json @@ -0,0 +1,37 @@ +{ + "main": "lib/index.js", + "scripts": { + "start": "npm run shell", + "compile": "tsc", + "build": "tsc", + "build:clean": "rm -rf ./lib", + "build:watch": "tsc --watch", + "serve": "npm run build && firebase emulators:start --only functions", + "shell": "npm run build && firebase functions:shell", + "deploy": "firebase deploy --only functions", + "logs": "firebase functions:log" + }, + "name": "functions", + "engines": { + "node": "20" + }, + "dependencies": { + "@genkit-ai/ai": "^0.5.0", + "@genkit-ai/core": "^0.5.0", + "@genkit-ai/dotprompt": "^0.5.0", + "@genkit-ai/firebase": "^0.5.0", + "@genkit-ai/flow": "^0.5.0", + "@genkit-ai/vertexai": "^0.5.0", + "express": "^4.19.2", + "firebase-admin": "^12.1.0", + "firebase-functions": "^5.0.0", + "partial-json": "^0.1.7", + "zod": "^3.23.8" + }, + "devDependencies": { + "firebase-functions-test": "^3.1.0", + "genkit": "^0.5.0", + "typescript": "^4.9.5" + }, + "private": true +} diff --git a/samples/js-firebase/functions/src/index.ts b/samples/js-firebase/functions/src/index.ts new file mode 100644 index 0000000000..baf3cd2052 --- /dev/null +++ b/samples/js-firebase/functions/src/index.ts @@ -0,0 +1,92 @@ +/** + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { generateStream } from '@genkit-ai/ai'; +import { configureGenkit } from '@genkit-ai/core'; +import { firebase } from '@genkit-ai/firebase'; +import { noAuth, onFlow } from '@genkit-ai/firebase/functions'; +import { geminiPro, vertexAI } from '@genkit-ai/vertexai'; +import { Allow, parse } from 'partial-json'; +import * as z from 'zod'; + +configureGenkit({ + plugins: [firebase(), vertexAI({ location: 'us-central1' })], + logLevel: 'debug', + enableTracingAndMetrics: true, +}); + +const GameCharactersSchema = z.object({ + characters: z + .array( + z + .object({ + name: z.string().describe('Name of a character'), + abilities: z + .array(z.string()) + .describe('Various abilities (strength, magic, archery, etc.)'), + }) + .describe('Game character') + ) + .describe('Characters'), +}); + +export const streamCharacters = onFlow( + { + name: 'streamCharacters', + inputSchema: z.number(), + outputSchema: z.string(), + streamSchema: GameCharactersSchema, + authPolicy: noAuth(), + httpsOptions: { + cors: '*', + }, + }, + async (count, streamingCallback) => { + if (!streamingCallback) { + throw new Error('this flow only works in streaming mode'); + } + + const { response, stream } = await generateStream({ + model: geminiPro, + output: { + schema: GameCharactersSchema, + }, + config: { + temperature: 1, + }, + prompt: `Respond as JSON only. Generate ${count} different RPG game characters.`, + }); + + let buffer = ''; + for await (const chunk of stream()) { + buffer += chunk.content[0].text!; + if (buffer.length > 10) { + streamingCallback(parse(maybeStripMarkdown(buffer), Allow.ALL)); + } + } + + return (await response()).text(); + } +); + +const markdownRegex = /^\s*(```json)?((.|\n)*?)(```)?\s*$/i; +function maybeStripMarkdown(withMarkdown: string) { + const mdMatch = markdownRegex.exec(withMarkdown); + if (!mdMatch) { + return withMarkdown; + } + return mdMatch[2]; +} diff --git a/samples/js-firebase/functions/tsconfig.json b/samples/js-firebase/functions/tsconfig.json new file mode 100644 index 0000000000..c927bfd28f --- /dev/null +++ b/samples/js-firebase/functions/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compileOnSave": true, + "include": ["src"], + "compilerOptions": { + "module": "commonjs", + "noImplicitReturns": true, + "outDir": "lib", + "sourceMap": true, + "strict": true, + "target": "es2017", + "skipLibCheck": true, + "esModuleInterop": true, + "noUnusedLocals": true + } +} diff --git a/samples/js-firebase/my-app/.editorconfig b/samples/js-firebase/my-app/.editorconfig new file mode 100644 index 0000000000..59d9a3a3e7 --- /dev/null +++ b/samples/js-firebase/my-app/.editorconfig @@ -0,0 +1,16 @@ +# Editor configuration, see https://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.ts] +quote_type = single + +[*.md] +max_line_length = off +trim_trailing_whitespace = false diff --git a/samples/js-firebase/my-app/.gitignore b/samples/js-firebase/my-app/.gitignore new file mode 100644 index 0000000000..cc7b141350 --- /dev/null +++ b/samples/js-firebase/my-app/.gitignore @@ -0,0 +1,42 @@ +# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files. + +# Compiled output +/dist +/tmp +/out-tsc +/bazel-out + +# Node +/node_modules +npm-debug.log +yarn-error.log + +# IDEs and editors +.idea/ +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# Visual Studio Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history/* + +# Miscellaneous +/.angular/cache +.sass-cache/ +/connect.lock +/coverage +/libpeerconnection.log +testem.log +/typings + +# System files +.DS_Store +Thumbs.db diff --git a/samples/js-firebase/my-app/README.md b/samples/js-firebase/my-app/README.md new file mode 100644 index 0000000000..fe2d6aea2c --- /dev/null +++ b/samples/js-firebase/my-app/README.md @@ -0,0 +1,27 @@ +# MyApp + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.3.7. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities. + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. diff --git a/samples/js-firebase/my-app/angular.json b/samples/js-firebase/my-app/angular.json new file mode 100644 index 0000000000..d5c6ba1b18 --- /dev/null +++ b/samples/js-firebase/my-app/angular.json @@ -0,0 +1,80 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "my-app": { + "projectType": "application", + "schematics": {}, + "root": "", + "sourceRoot": "src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:application", + "options": { + "outputPath": "dist/my-app", + "index": "src/index.html", + "browser": "src/main.ts", + "polyfills": ["zone.js"], + "tsConfig": "tsconfig.app.json", + "assets": ["src/favicon.ico", "src/assets"], + "styles": ["src/styles.css"], + "scripts": [] + }, + "configurations": { + "production": { + "budgets": [ + { + "type": "initial", + "maximumWarning": "500kb", + "maximumError": "1mb" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "2kb", + "maximumError": "4kb" + } + ], + "outputHashing": "all" + }, + "development": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true + } + }, + "defaultConfiguration": "production" + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "configurations": { + "production": { + "buildTarget": "my-app:build:production" + }, + "development": { + "buildTarget": "my-app:build:development" + } + }, + "defaultConfiguration": "development" + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "buildTarget": "my-app:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "polyfills": ["zone.js", "zone.js/testing"], + "tsConfig": "tsconfig.spec.json", + "assets": ["src/favicon.ico", "src/assets"], + "styles": ["src/styles.css"], + "scripts": [] + } + } + } + } + } +} diff --git a/samples/js-firebase/my-app/package.json b/samples/js-firebase/my-app/package.json new file mode 100644 index 0000000000..984b9d70cd --- /dev/null +++ b/samples/js-firebase/my-app/package.json @@ -0,0 +1,38 @@ +{ + "name": "my-app", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "watch": "ng build --watch --configuration development", + "test": "ng test" + }, + "private": true, + "dependencies": { + "@angular/animations": "^17.3.0", + "@angular/common": "^17.3.0", + "@angular/compiler": "^17.3.0", + "@angular/core": "^17.3.0", + "@angular/forms": "^17.3.0", + "@angular/platform-browser": "^17.3.0", + "@angular/platform-browser-dynamic": "^17.3.0", + "@angular/router": "^17.3.0", + "rxjs": "~7.8.0", + "tslib": "^2.3.0", + "zone.js": "~0.14.3" + }, + "devDependencies": { + "@angular-devkit/build-angular": "^17.3.7", + "@angular/cli": "^17.3.7", + "@angular/compiler-cli": "^17.3.0", + "@types/jasmine": "~5.1.0", + "jasmine-core": "~5.1.0", + "karma": "~6.4.0", + "karma-chrome-launcher": "~3.2.0", + "karma-coverage": "~2.2.0", + "karma-jasmine": "~5.1.0", + "karma-jasmine-html-reporter": "~2.1.0", + "typescript": "~5.4.2" + } +} diff --git a/samples/js-firebase/my-app/src/app/app.component.css b/samples/js-firebase/my-app/src/app/app.component.css new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samples/js-firebase/my-app/src/app/app.component.html b/samples/js-firebase/my-app/src/app/app.component.html new file mode 100644 index 0000000000..17d1020388 --- /dev/null +++ b/samples/js-firebase/my-app/src/app/app.component.html @@ -0,0 +1,34 @@ + + +