From c8572336c2dda9d6dedf2743a67237922605d7bd Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Fri, 11 Apr 2025 09:20:42 -0700 Subject: [PATCH 1/9] Add apphosting.yaml --- .gitignore | 69 +++++++++++++++++++++++++++++++++++++++++++++++++ apphosting.yaml | 23 +++++++++++++++++ firebase.json | 1 + 3 files changed, 93 insertions(+) create mode 100644 .gitignore create mode 100644 apphosting.yaml create mode 100644 firebase.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0461ddf --- /dev/null +++ b/.gitignore @@ -0,0 +1,69 @@ +# 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 + +# dataconnect generated files +.dataconnect diff --git a/apphosting.yaml b/apphosting.yaml new file mode 100644 index 0000000..c10a280 --- /dev/null +++ b/apphosting.yaml @@ -0,0 +1,23 @@ +# Settings for Backend (on Cloud Run). +# See https://firebase.google.com/docs/app-hosting/configure#cloud-run +runConfig: + minInstances: 0 + # maxInstances: 100 + # concurrency: 80 + # cpu: 1 + # memoryMiB: 512 + +# Environment variables and secrets. +env: + # Configure environment variables. + # See https://firebase.google.com/docs/app-hosting/configure#user-defined-environment + # - variable: MESSAGE + # value: Hello world! + # availability: + # - BUILD + # - RUNTIME + + # Grant access to secrets in Cloud Secret Manager. + # See https://firebase.google.com/docs/app-hosting/configure#secret-parameters + - variable: GEMINI_API_KEY + secret: GEMINI_API_KEY diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/firebase.json @@ -0,0 +1 @@ +{} From 0859a1d79f2f8ae064a895a634841de055d2cf89 Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Fri, 11 Apr 2025 10:03:02 -0700 Subject: [PATCH 2/9] Add img logging --- genkit-angular-story-generator/src/flows.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/genkit-angular-story-generator/src/flows.ts b/genkit-angular-story-generator/src/flows.ts index 6239806..9fe9f54 100644 --- a/genkit-angular-story-generator/src/flows.ts +++ b/genkit-angular-story-generator/src/flows.ts @@ -267,7 +267,8 @@ const imgBlobFlow = ai.defineFlow( output: { format: 'media' }, }); return response.message!.content[0].media!.url; - } catch { + } catch(e) { + console.log(e); return ''; } } From 3a8b89d9f73705f10520f8bb6bb515ee36a6daec Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Fri, 11 Apr 2025 10:21:14 -0700 Subject: [PATCH 3/9] Adjust img prompt --- genkit-angular-story-generator/src/flows.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/genkit-angular-story-generator/src/flows.ts b/genkit-angular-story-generator/src/flows.ts index 9fe9f54..ce317ae 100644 --- a/genkit-angular-story-generator/src/flows.ts +++ b/genkit-angular-story-generator/src/flows.ts @@ -248,7 +248,8 @@ async function genImgBlob(story: string, sessionId: string): Promise { const chat = session.chat({ sessionId, model }); const { text: storyImgDescr } = await chat.send(` Describe an image that the captures the essence of this story: ${story}. - Do not use any words indicating violence or profanity. Return a string only.`); + Do not use any words indicating violence or profanity. Return a string only. + Do not return JSON.`); const imgPrompt = createImgPrompt(storyImgDescr); return await imgBlobFlow(imgPrompt); } From 276135fd37dc7882106697870473eeda71f3ab4c Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Fri, 11 Apr 2025 10:54:10 -0700 Subject: [PATCH 4/9] Update img prompt --- genkit-angular-story-generator/src/prompts.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/genkit-angular-story-generator/src/prompts.ts b/genkit-angular-story-generator/src/prompts.ts index 0e8748f..d501f9c 100644 --- a/genkit-angular-story-generator/src/prompts.ts +++ b/genkit-angular-story-generator/src/prompts.ts @@ -215,6 +215,6 @@ export function beginStoryPrompt(description: string): string { } export function createImgPrompt(story: string): string { - return `Create picture of ${String(story)}. It should be in an illustrative, storybook style. + return `Create picture of ${String(story)}. It should be in an photo-realistic style. Do not include any words or modals in the image.`; } \ No newline at end of file From b33241c4377208186b5777cd835dc2353f8a73cc Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Fri, 11 Apr 2025 11:08:26 -0700 Subject: [PATCH 5/9] Update story component --- .../src/app/story/story.component.html | 2 +- genkit-angular-story-generator/src/app/story/story.component.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/genkit-angular-story-generator/src/app/story/story.component.html b/genkit-angular-story-generator/src/app/story/story.component.html index 233bb2a..a77c40e 100644 --- a/genkit-angular-story-generator/src/app/story/story.component.html +++ b/genkit-angular-story-generator/src/app/story/story.component.html @@ -7,7 +7,7 @@ * found in the LICENSE file at https://angular.dev/license * --> - @if (!storyResource.isLoading() || storyService.hasStoryStarted()) { + @if (storyParts().length > 0) {
Your primary objective:
diff --git a/genkit-angular-story-generator/src/app/story/story.component.ts b/genkit-angular-story-generator/src/app/story/story.component.ts index b380ad0..f9e046e 100644 --- a/genkit-angular-story-generator/src/app/story/story.component.ts +++ b/genkit-angular-story-generator/src/app/story/story.component.ts @@ -20,7 +20,7 @@ const DEFAULT_STORY: StoryData = { primaryObjective: '', storyParts: [], options: [], - rating: 'NEUTRAL', + rating: '', progress: 0 }; From 2af07e14c451de601499a93818867bd7fbd7fbe7 Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Mon, 14 Apr 2025 08:22:56 -0700 Subject: [PATCH 6/9] Add persistent session storage --- genkit-angular-story-generator/.gitignore | 3 ++ genkit-angular-story-generator/src/flows.ts | 56 +++++++++++++++++---- 2 files changed, 49 insertions(+), 10 deletions(-) diff --git a/genkit-angular-story-generator/.gitignore b/genkit-angular-story-generator/.gitignore index 0d4c46a..828fae8 100644 --- a/genkit-angular-story-generator/.gitignore +++ b/genkit-angular-story-generator/.gitignore @@ -107,3 +107,6 @@ node_modules/ # dataconnect generated files .dataconnect +# session data +session-stores/ + diff --git a/genkit-angular-story-generator/src/flows.ts b/genkit-angular-story-generator/src/flows.ts index ce317ae..35b73c8 100644 --- a/genkit-angular-story-generator/src/flows.ts +++ b/genkit-angular-story-generator/src/flows.ts @@ -5,12 +5,13 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ -import { Chat, genkit, Session } from "genkit/beta"; +import { Chat, genkit, Session, SessionData, SessionStore } from "genkit/beta"; import { z } from "zod"; import { imagen3Fast, vertexAI, gemini15Pro } from '@genkit-ai/vertexai'; import { googleAI, gemini20Flash } from "@genkit-ai/googleai"; import { beginStoryPrompt, createImgPrompt, continuePrompt, descriptionPrompt, preamblePrompt } from './prompts'; import { parse } from 'partial-json'; +import { readFile, writeFile } from "node:fs/promises"; // Defined twice to easily swap models const model = gemini20Flash; @@ -28,8 +29,7 @@ interface MyState { primaryObjective?: string; milestones?: string[]; currentMilestone?: string; - } -let session: Session; +} const DescriptionOutput = z.object({ storyPremise: z.string(), @@ -49,11 +49,15 @@ export const descriptionFlow = ai.defineFlow( }, async ({ userInput, sessionId, clearSession }) => { let chat: Chat; - if (clearSession || !session) { - session = ai.createSession({ - sessionId, - initialState: {}, - }); + + let session = ai.createSession({ + store: new JsonSessionStore(), + sessionId, + initialState: {} + }); + + if (clearSession) { + session.updateState({}); chat = session.chat(preamble, { sessionId, model }); await session.updateMessages(sessionId, []); } else { @@ -96,7 +100,7 @@ export const beginStoryFlow = ai.defineFlow( name: 'beginStoryFlow', inputSchema: z.object({ userInput: z.string(), - sessionId: z.string() + sessionId: z.string(), }), outputSchema: StoryOutput }, @@ -105,6 +109,9 @@ export const beginStoryFlow = ai.defineFlow( let options: string[] = []; let primaryObjective = ''; try { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); const chat = session.chat({ sessionId, model }); const { text } = await chat.send(beginStoryPrompt(userInput)); let storyDetail: z.infer; @@ -148,6 +155,9 @@ export const continueStoryFlow = ai.defineFlow( outputSchema: StoryOutput.extend({ rating: z.string() }) }, async ({ userInput, sessionId}) => { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); const chat = session.chat({ sessionId, model }); let storyParts: string[] = []; @@ -190,6 +200,9 @@ async function handleProgress( storyParts: string[], achievedMilestone: boolean, sessionId: string): Promise<{ storyParts: string[], progress: number }> { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); let currentMilestone = session.state.currentMilestone; const milestones = session.state.milestones; const finalMilestone = milestones[milestones.length - 1]; @@ -215,6 +228,9 @@ const endStoryFlow = ai.defineFlow( }, async (sessionId) => { try { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); const chat = session.chat({ sessionId, model }); const { text } = await chat.send(` The characters have achieved their primary objective. @@ -245,6 +261,9 @@ export const genImgFlow = ai.defineFlow( ); async function genImgBlob(story: string, sessionId: string): Promise { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); const chat = session.chat({ sessionId, model }); const { text: storyImgDescr } = await chat.send(` Describe an image that the captures the essence of this story: ${story}. @@ -282,4 +301,21 @@ function maybeStripMarkdown(withMarkdown: string) { return withMarkdown; } return mdMatch[2]; -} \ No newline at end of file +} + +class JsonSessionStore implements SessionStore { + async get(sessionId: string): Promise | undefined> { + try { + const s = await readFile(`session-stores/${sessionId}.json`, { encoding: 'utf8'}); + const data = JSON.parse(s); + return data; + } catch { + return undefined; + } + } + + async save(sessionId: string, sessionData: SessionData): Promise { + const s = JSON.stringify(sessionData); + await writeFile(`session-stores/${sessionId}.json`, s, { encoding: 'utf8' }); + } +} From 80dc67407a62d22a810214f4e25ad9bd440414f3 Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Mon, 14 Apr 2025 14:45:20 -0400 Subject: [PATCH 7/9] Use global var for session mgmt --- genkit-angular-story-generator/.gitignore | 3 - .../src/app/story.service.ts | 2 +- .../app/user-input/user-input.component.html | 2 +- .../app/user-input/user-input.component.ts | 1 + genkit-angular-story-generator/src/flows.ts | 437 +++++++++--------- 5 files changed, 222 insertions(+), 223 deletions(-) diff --git a/genkit-angular-story-generator/.gitignore b/genkit-angular-story-generator/.gitignore index 828fae8..0d4c46a 100644 --- a/genkit-angular-story-generator/.gitignore +++ b/genkit-angular-story-generator/.gitignore @@ -107,6 +107,3 @@ node_modules/ # dataconnect generated files .dataconnect -# session data -session-stores/ - diff --git a/genkit-angular-story-generator/src/app/story.service.ts b/genkit-angular-story-generator/src/app/story.service.ts index 0db843f..ac0cca6 100644 --- a/genkit-angular-story-generator/src/app/story.service.ts +++ b/genkit-angular-story-generator/src/app/story.service.ts @@ -5,7 +5,7 @@ * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ -import { Injectable, signal, linkedSignal, resource, computed } from '@angular/core'; +import { Injectable, signal, linkedSignal, resource } from '@angular/core'; import { runFlow } from 'genkit/beta/client'; export const DESCRIPTION_FLOW = 'descriptionFlow'; diff --git a/genkit-angular-story-generator/src/app/user-input/user-input.component.html b/genkit-angular-story-generator/src/app/user-input/user-input.component.html index 61de506..50ae8e1 100644 --- a/genkit-angular-story-generator/src/app/user-input/user-input.component.html +++ b/genkit-angular-story-generator/src/app/user-input/user-input.component.html @@ -34,7 +34,7 @@

{{isDescriptionFlow() ? nextQuestion : "What should you do next?"}}

@let continueButtonText = storyService.hasStoryStarted() ? 'See what happens next' : 'Begin your adventure'; {{isDescriptionFlow() ? 'Next question' : continueButtonText}} - @if (storyService.hasPremiseUpdated()) { + @if (storyService.hasPremiseUpdated() && !storyService.premiseResource.isLoading()) { }
diff --git a/genkit-angular-story-generator/src/app/user-input/user-input.component.ts b/genkit-angular-story-generator/src/app/user-input/user-input.component.ts index 9e8d040..e16295d 100644 --- a/genkit-angular-story-generator/src/app/user-input/user-input.component.ts +++ b/genkit-angular-story-generator/src/app/user-input/user-input.component.ts @@ -37,6 +37,7 @@ export class UserInputComponent { } onSubmit(): void { + console.log(this.storyService.sessionId()); if (this.isDescriptionFlow()) { this.storyService.premiseInput.set(this.userInput); } else { diff --git a/genkit-angular-story-generator/src/flows.ts b/genkit-angular-story-generator/src/flows.ts index 35b73c8..ba62bf1 100644 --- a/genkit-angular-story-generator/src/flows.ts +++ b/genkit-angular-story-generator/src/flows.ts @@ -11,7 +11,6 @@ import { imagen3Fast, vertexAI, gemini15Pro } from '@genkit-ai/vertexai'; import { googleAI, gemini20Flash } from "@genkit-ai/googleai"; import { beginStoryPrompt, createImgPrompt, continuePrompt, descriptionPrompt, preamblePrompt } from './prompts'; import { parse } from 'partial-json'; -import { readFile, writeFile } from "node:fs/promises"; // Defined twice to easily swap models const model = gemini20Flash; @@ -21,167 +20,169 @@ const ai = genkit({ }); const preamble = ai.definePrompt( - { name: 'preamble' }, - preamblePrompt + { name: 'preamble' }, + preamblePrompt ); interface MyState { - primaryObjective?: string; - milestones?: string[]; - currentMilestone?: string; + primaryObjective?: string; + milestones?: string[]; + currentMilestone?: string; } const DescriptionOutput = z.object({ - storyPremise: z.string(), - nextQuestion: z.string(), - premiseOptions: z.array(z.string()) + storyPremise: z.string(), + nextQuestion: z.string(), + premiseOptions: z.array(z.string()) }); export const descriptionFlow = ai.defineFlow( - { - name: 'descriptionFlow', - inputSchema: z.object({ - userInput: z.optional(z.string()), - sessionId: z.string(), - clearSession: z.boolean() - }), - outputSchema: DescriptionOutput - }, - async ({ userInput, sessionId, clearSession }) => { - let chat: Chat; + { + name: 'descriptionFlow', + inputSchema: z.object({ + userInput: z.optional(z.string()), + sessionId: z.string(), + clearSession: z.boolean() + }), + outputSchema: DescriptionOutput + }, + async ({ userInput, sessionId, clearSession }) => { + let chat: Chat; - let session = ai.createSession({ - store: new JsonSessionStore(), - sessionId, - initialState: {} - }); - - if (clearSession) { - session.updateState({}); - chat = session.chat(preamble, { sessionId, model }); - await session.updateMessages(sessionId, []); - } else { - chat = session.chat({ sessionId, model }); - } - try { - const { text } = await chat.send(descriptionPrompt(userInput || '')); - return parse(maybeStripMarkdown(text)); - } catch { - return { - storyPremise: '', - nextQuestion: 'Tell me more about the story', - premiseOptions: [] - } - } + if (clearSession) { + const session = ai.createSession({ + store: new JsonSessionStore(), + sessionId, + initialState: {} + }); + session.updateState({}); + chat = session.chat(preamble, { sessionId, model }); + await session.updateMessages(sessionId, []); + } else { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); + chat = session.chat({ sessionId, model }); } + try { + const { text } = await chat.send(descriptionPrompt(userInput || '')); + return parse(maybeStripMarkdown(text)); + } catch { + return { + storyPremise: '', + nextQuestion: 'Tell me more about the story', + premiseOptions: [] + } + } + } ); const StoryDetail = z.object({ - story: z.optional(z.string()), - storyParts: z.array(z.string()), - primaryObjective: z.string(), - milestones: z.array(z.string()), - progress: z.number(), - choices: z.array(z.object({ - choice: z.string(), - rating: z.string() - })) + story: z.optional(z.string()), + storyParts: z.array(z.string()), + primaryObjective: z.string(), + milestones: z.array(z.string()), + progress: z.number(), + choices: z.array(z.object({ + choice: z.string(), + rating: z.string() + })) }); const StoryOutput = z.object({ - storyParts: z.array(z.string()), - options: z.array(z.string()), - primaryObjective: z.string(), - progress: z.number() + storyParts: z.array(z.string()), + options: z.array(z.string()), + primaryObjective: z.string(), + progress: z.number() }); export const beginStoryFlow = ai.defineFlow( - { - name: 'beginStoryFlow', - inputSchema: z.object({ - userInput: z.string(), - sessionId: z.string(), - }), - outputSchema: StoryOutput - }, - async ({ userInput, sessionId }) => { - let storyParts: string[] = []; - let options: string[] = []; - let primaryObjective = ''; - try { - const session = await ai.loadSession(sessionId, { - store: new JsonSessionStore(), - }); - const chat = session.chat({ sessionId, model }); - const { text } = await chat.send(beginStoryPrompt(userInput)); - let storyDetail: z.infer; - storyDetail = parse(maybeStripMarkdown(text)); - storyParts = storyDetail.storyParts; - primaryObjective = storyDetail.primaryObjective; - session.updateState({ - primaryObjective, - milestones: storyDetail.milestones, - currentMilestone: storyDetail.milestones[0] - }); - storyDetail.progress = 0; - options = storyDetail.choices.map(choice => choice.choice); - } catch (e) { - console.log(e); - } - return { storyParts, options, progress: 0, primaryObjective }; + { + name: 'beginStoryFlow', + inputSchema: z.object({ + userInput: z.string(), + sessionId: z.string(), + }), + outputSchema: StoryOutput + }, + async ({ userInput, sessionId }) => { + let storyParts: string[] = []; + let options: string[] = []; + let primaryObjective = ''; + try { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); + const chat = session.chat({ sessionId, model }); + const { text } = await chat.send(beginStoryPrompt(userInput)); + let storyDetail: z.infer; + storyDetail = parse(maybeStripMarkdown(text)); + storyParts = storyDetail.storyParts; + primaryObjective = storyDetail.primaryObjective; + session.updateState({ + primaryObjective, + milestones: storyDetail.milestones, + currentMilestone: storyDetail.milestones[0] + }); + storyDetail.progress = 0; + options = storyDetail.choices.map(choice => choice.choice); + } catch (e) { + console.log(e); } + return { storyParts, options, progress: 0, primaryObjective }; + } ); const ContStoryDetail = z.object({ - story: z.optional(z.string()), - storyParts: z.array(z.string()), - rating: z.string(), - primaryObjective: z.string(), - achievedCurrentMilestone: z.boolean(), - progress: z.number(), - choices: z.array(z.object({ - choice: z.string(), - rating: z.string() - })), + story: z.optional(z.string()), + storyParts: z.array(z.string()), + rating: z.string(), + primaryObjective: z.string(), + achievedCurrentMilestone: z.boolean(), + progress: z.number(), + choices: z.array(z.object({ + choice: z.string(), + rating: z.string() + })), }); export const continueStoryFlow = ai.defineFlow( - { - name: 'continueStoryFlow', - inputSchema: z.object({ - userInput: z.string(), - sessionId: z.string() - }), - outputSchema: StoryOutput.extend({ rating: z.string() }) - }, - async ({ userInput, sessionId}) => { - const session = await ai.loadSession(sessionId, { - store: new JsonSessionStore(), - }); - const chat = session.chat({ sessionId, model }); + { + name: 'continueStoryFlow', + inputSchema: z.object({ + userInput: z.string(), + sessionId: z.string() + }), + outputSchema: StoryOutput.extend({ rating: z.string() }) + }, + async ({ userInput, sessionId }) => { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); + const chat = session.chat({ sessionId, model }); - let storyParts: string[] = []; - let options: string[] = []; - let rating: string = 'NEUTRAL'; - let primaryObjective = session.state.primaryObjective; - let progress = -1; + let storyParts: string[] = []; + let options: string[] = []; + let rating: string = 'NEUTRAL'; + let primaryObjective = session.state.primaryObjective; + let progress = -1; - try { - const { text } = await chat.send(continuePrompt(userInput, session.state.currentMilestone)); - const storyDetail: z.infer = parse(maybeStripMarkdown(text)); - storyParts = storyDetail.storyParts; - options = storyDetail.choices.map(choice => choice.choice); - rating = storyDetail.rating; - const acheivedMilestone = storyDetail.achievedCurrentMilestone; - const progressResponse = await handleProgress(storyParts, acheivedMilestone, sessionId); - storyParts = progressResponse.storyParts; - progress = progressResponse.progress; - primaryObjective = session.state.primaryObjective; - } catch (e) { - console.log(e); - } - return { storyParts, options, primaryObjective, progress, rating }; + try { + const { text } = await chat.send(continuePrompt(userInput, session.state.currentMilestone)); + const storyDetail: z.infer = parse(maybeStripMarkdown(text)); + storyParts = storyDetail.storyParts; + options = storyDetail.choices.map(choice => choice.choice); + rating = storyDetail.rating; + const acheivedMilestone = storyDetail.achievedCurrentMilestone; + const progressResponse = await handleProgress(storyParts, acheivedMilestone, sessionId); + storyParts = progressResponse.storyParts; + progress = progressResponse.progress; + primaryObjective = session.state.primaryObjective; + } catch (e) { + console.log(e); } + return { storyParts, options, primaryObjective, progress, rating }; + } ); /** @@ -197,101 +198,101 @@ export const continueStoryFlow = ai.defineFlow( * @returns updated storyParts and progress */ async function handleProgress( - storyParts: string[], - achievedMilestone: boolean, - sessionId: string): Promise<{ storyParts: string[], progress: number }> { - const session = await ai.loadSession(sessionId, { - store: new JsonSessionStore(), - }); - let currentMilestone = session.state.currentMilestone; - const milestones = session.state.milestones; - const finalMilestone = milestones[milestones.length - 1]; - let progress = milestones.indexOf(currentMilestone) / milestones.length; - if (achievedMilestone && currentMilestone === finalMilestone) { - progress = 1; - const storyEnding = await endStoryFlow(sessionId); - storyParts = [...storyParts, ...storyEnding]; - } else if (achievedMilestone) { - const nextMilestoneIndex = milestones.indexOf(currentMilestone) + 1; - currentMilestone = milestones[nextMilestoneIndex]; - progress = nextMilestoneIndex / milestones.length; - session.updateState({ ...session.state, currentMilestone }); - } - return { storyParts, progress }; + storyParts: string[], + achievedMilestone: boolean, + sessionId: string): Promise<{ storyParts: string[], progress: number }> { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); + let currentMilestone = session.state.currentMilestone; + const milestones = session.state.milestones; + const finalMilestone = milestones[milestones.length - 1]; + let progress = milestones.indexOf(currentMilestone) / milestones.length; + if (achievedMilestone && currentMilestone === finalMilestone) { + progress = 1; + const storyEnding = await endStoryFlow(sessionId); + storyParts = [...storyParts, ...storyEnding]; + } else if (achievedMilestone) { + const nextMilestoneIndex = milestones.indexOf(currentMilestone) + 1; + currentMilestone = milestones[nextMilestoneIndex]; + progress = nextMilestoneIndex / milestones.length; + session.updateState({ ...session.state, currentMilestone }); + } + return { storyParts, progress }; } const endStoryFlow = ai.defineFlow( - { - name: 'endStoryFlow', - inputSchema: z.string(), - outputSchema: z.array(z.string()) - }, - async (sessionId) => { - try { - const session = await ai.loadSession(sessionId, { - store: new JsonSessionStore(), - }); - const chat = session.chat({ sessionId, model }); - const { text } = await chat.send(` - The characters have achieved their primary objective. - Write the conclusion of the story. Don't repeat any - of the story. This next part should be a max of 200 words. - Split the story into 3 parts of similar length. Return an - array of strings with the story parts. - `); - return parse(maybeStripMarkdown(text)); - } catch { - return []; - } - } + { + name: 'endStoryFlow', + inputSchema: z.string(), + outputSchema: z.array(z.string()) + }, + async (sessionId) => { + try { + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); + const chat = session.chat({ sessionId, model }); + const { text } = await chat.send(` + The characters have achieved their primary objective. + Write the conclusion of the story. Don't repeat any + of the story. This next part should be a max of 200 words. + Split the story into 3 parts of similar length. Return an + array of strings with the story parts. + `); + return parse(maybeStripMarkdown(text)); + } catch { + return []; + } + } ); export const genImgFlow = ai.defineFlow( - { - name: 'genImgFlow', - inputSchema: z.object({ - story: z.string(), - sessionId: z.string() - }), - outputSchema: z.string() - }, - async ({ story, sessionId }) => { - return await genImgBlob(story, sessionId); - } + { + name: 'genImgFlow', + inputSchema: z.object({ + story: z.string(), + sessionId: z.string() + }), + outputSchema: z.string() + }, + async ({ story, sessionId }) => { + return await genImgBlob(story, sessionId); + } ); async function genImgBlob(story: string, sessionId: string): Promise { - const session = await ai.loadSession(sessionId, { - store: new JsonSessionStore(), - }); - const chat = session.chat({ sessionId, model }); - const { text: storyImgDescr } = await chat.send(` + const session = await ai.loadSession(sessionId, { + store: new JsonSessionStore(), + }); + const chat = session.chat({ sessionId, model }); + const { text: storyImgDescr } = await chat.send(` Describe an image that the captures the essence of this story: ${story}. Do not use any words indicating violence or profanity. Return a string only. Do not return JSON.`); - const imgPrompt = createImgPrompt(storyImgDescr); - return await imgBlobFlow(imgPrompt); + const imgPrompt = createImgPrompt(storyImgDescr); + return await imgBlobFlow(imgPrompt); } const imgBlobFlow = ai.defineFlow( - { - name: 'imgBlobFlow', - inputSchema: z.string(), - outputSchema: z.string() - }, - async (prompt) => { - try { - const response = await ai.generate({ - model: imagen3Fast, - prompt, - output: { format: 'media' }, - }); - return response.message!.content[0].media!.url; - } catch(e) { - console.log(e); - return ''; - } + { + name: 'imgBlobFlow', + inputSchema: z.string(), + outputSchema: z.string() + }, + async (prompt) => { + try { + const response = await ai.generate({ + model: imagen3Fast, + prompt, + output: { format: 'media' }, + }); + return response.message!.content[0].media!.url; + } catch (e) { + console.log(e); + return ''; } + } ); const markdownRegex = /^\s*(```json)?((.|\n)*?)(```)?\s*$/i; @@ -303,19 +304,19 @@ function maybeStripMarkdown(withMarkdown: string) { return mdMatch[2]; } +// For demonstration purposes only. It is recommended to use a proper data +// store in a production application. +const sessionStore: { [key: string]: SessionData } = {}; class JsonSessionStore implements SessionStore { async get(sessionId: string): Promise | undefined> { - try { - const s = await readFile(`session-stores/${sessionId}.json`, { encoding: 'utf8'}); - const data = JSON.parse(s); - return data; - } catch { + if (sessionId in sessionStore) + return sessionStore[sessionId]; + else { return undefined; } } async save(sessionId: string, sessionData: SessionData): Promise { - const s = JSON.stringify(sessionData); - await writeFile(`session-stores/${sessionId}.json`, s, { encoding: 'utf8' }); + sessionStore[sessionId] = sessionData; } } From 7bb5bcb65abf2034c2ff4f87c42910312eeee508 Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Mon, 14 Apr 2025 15:27:11 -0400 Subject: [PATCH 8/9] Remove console log --- .../src/app/user-input/user-input.component.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/genkit-angular-story-generator/src/app/user-input/user-input.component.ts b/genkit-angular-story-generator/src/app/user-input/user-input.component.ts index e16295d..9e8d040 100644 --- a/genkit-angular-story-generator/src/app/user-input/user-input.component.ts +++ b/genkit-angular-story-generator/src/app/user-input/user-input.component.ts @@ -37,7 +37,6 @@ export class UserInputComponent { } onSubmit(): void { - console.log(this.storyService.sessionId()); if (this.isDescriptionFlow()) { this.storyService.premiseInput.set(this.userInput); } else { From 436df55810639c0833926aa2c5bed5a3dc524fa9 Mon Sep 17 00:00:00 2001 From: Devin Chasanoff Date: Mon, 14 Apr 2025 15:37:51 -0400 Subject: [PATCH 9/9] Fix update button bug --- .../src/app/user-input/user-input.component.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/genkit-angular-story-generator/src/app/user-input/user-input.component.html b/genkit-angular-story-generator/src/app/user-input/user-input.component.html index 50ae8e1..588c5c2 100644 --- a/genkit-angular-story-generator/src/app/user-input/user-input.component.html +++ b/genkit-angular-story-generator/src/app/user-input/user-input.component.html @@ -34,7 +34,7 @@

{{isDescriptionFlow() ? nextQuestion : "What should you do next?"}}

@let continueButtonText = storyService.hasStoryStarted() ? 'See what happens next' : 'Begin your adventure'; {{isDescriptionFlow() ? 'Next question' : continueButtonText}} - @if (storyService.hasPremiseUpdated() && !storyService.premiseResource.isLoading()) { + @if (storyService.hasPremiseUpdated() && !storyService.premiseResource.isLoading() && !this.storyService.hasStoryStarted()) { }