Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions samples/js-firebase/.firebaserc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
66 changes: 66 additions & 0 deletions samples/js-firebase/.gitignore
Original file line number Diff line number Diff line change
@@ -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
17 changes: 17 additions & 0 deletions samples/js-firebase/README.md
Original file line number Diff line number Diff line change
@@ -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
19 changes: 19 additions & 0 deletions samples/js-firebase/firebase.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
}
10 changes: 10 additions & 0 deletions samples/js-firebase/functions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Compiled JavaScript files
lib/**/*.js
lib/**/*.js.map

# TypeScript v1 declaration files
typings/

# Node.js dependency directory
node_modules/
*.local
37 changes: 37 additions & 0 deletions samples/js-firebase/functions/package.json
Original file line number Diff line number Diff line change
@@ -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
}
92 changes: 92 additions & 0 deletions samples/js-firebase/functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -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];
}
15 changes: 15 additions & 0 deletions samples/js-firebase/functions/tsconfig.json
Original file line number Diff line number Diff line change
@@ -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
}
}
16 changes: 16 additions & 0 deletions samples/js-firebase/my-app/.editorconfig
Original file line number Diff line number Diff line change
@@ -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
42 changes: 42 additions & 0 deletions samples/js-firebase/my-app/.gitignore
Original file line number Diff line number Diff line change
@@ -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
27 changes: 27 additions & 0 deletions samples/js-firebase/my-app/README.md
Original file line number Diff line number Diff line change
@@ -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.
Loading