diff --git a/adev-ja/src/app/sub-navigation-data.en.ts b/adev-ja/src/app/sub-navigation-data.en.ts index e7bcf46353..8124d3200d 100644 --- a/adev-ja/src/app/sub-navigation-data.en.ts +++ b/adev-ja/src/app/sub-navigation-data.en.ts @@ -685,6 +685,11 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [ path: 'ai/develop-with-ai', contentPath: 'ai/develop-with-ai', }, + { + label: 'Design Patterns', + path: 'ai/design-patterns', + contentPath: 'ai/design-patterns', + }, { label: 'Angular CLI MCP Server setup', path: 'ai/mcp', diff --git a/adev-ja/src/app/sub-navigation-data.ts b/adev-ja/src/app/sub-navigation-data.ts index 9d9a55f30f..6f0ff1a1a4 100644 --- a/adev-ja/src/app/sub-navigation-data.ts +++ b/adev-ja/src/app/sub-navigation-data.ts @@ -685,6 +685,11 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [ path: 'ai/develop-with-ai', contentPath: 'ai/develop-with-ai', }, + { + label: '設計パターン', + path: 'ai/design-patterns', + contentPath: 'ai/design-patterns', + }, { label: 'Angular CLI MCPサーバーセットアップ', path: 'ai/mcp', diff --git a/adev-ja/src/content/ai/design-patterns.md b/adev-ja/src/content/ai/design-patterns.md new file mode 100644 index 0000000000..6dfe51aba4 --- /dev/null +++ b/adev-ja/src/content/ai/design-patterns.md @@ -0,0 +1,172 @@ +# Design patterns for AI SDKs and signal APIs + +Interacting with AI and Large Language Model (LLM) APIs introduces unique challenges, such as managing asynchronous operations, handling streaming data, and designing a responsive user experience for potentially slow or unreliable network requests. Angular [signals](guide/signals) and the [`resource`](guide/signals/resource) API provide powerful tools to solve these problems elegantly. + +## Triggering requests with signals + +A common pattern when working with user-provided prompts is to separate the user's live input from the submitted value that triggers the API call. + +1. Store the user's raw input in one signal as they type +2. When the user submits (e.g., by clicking a button), update a second signal with contents of the first signal. +3. Use the second signal in the **`params`** field of your `resource`. + +This setup ensures the resource's **`loader`** function only runs when the user explicitly submits their prompt, not on every keystroke. You can use additional signal parameters, like a `sessionId` or `userId` (which can be useful for creating persistent LLM sessions), in the `loader` field. This way, the request always uses these parameters' current values without re-triggering the asyncronous function defined in the `loader` field. + +Many AI SDKs provide helper methods for making API calls. For example, the Genkit client library exposes a `runFlow` method for calling Genkit flows, which you can call from a resource's `loader`. For other APIs, you can use the [`httpResource`](guide/signals/resource#reactive-data-fetching-with-httpresource). + +The following example shows a `resource` that fetches parts of an AI-generated story. The `loader` is triggered only when the `storyInput` signal changes. + +```ts +// A resource that fetches three parts of an AI generated story +storyResource = resource({ + // The default value to use before the first request or on error + defaultValue: DEFAULT_STORY, + // The loader is re-triggered when this signal changes + params: () => this.storyInput(), + // The async function to fetch data + loader: ({params}): Promise => { + // The params value is the current value of the storyInput signal + const url = this.endpoint(); + return runFlow({ url, input: { + userInput: params, + sessionId: this.storyService.sessionId() // Read from another signal + }}); + } +}); +``` + +## Preparing LLM data for templates + +You can configure LLM APIs to return structured data. Strongly typing your `resource` to match the expected output from the LLM provides better type safety and editor autocompletion. + +To manage state derived from a resource, use a `computed` signal or `linkedSignal`. Because `linkedSignal` [provides access to prior values](guide/signals/linked-signal), it can serve a variety of AI-related use cases, including + * building a chat history + * preserving or customizing data that templates display while LLMs generate content + +In the example below, `storyParts` is a `linkedSignal` that appends the latest story parts returned from `storyResource` to the existing array of story parts. + +```ts +storyParts = linkedSignal({ + // The source signal that triggers the computation + source: () => this.storyResource.value().storyParts, + // The computation function + computation: (newStoryParts, previous) => { + // Get the previous value of this linkedSignal, or an empty array + const existingStoryParts = previous?.value || []; + // Return a new array with the old and new parts + return [...existingStoryParts, ...newStoryParts]; + } +}); +``` + +## Performance and user experience + +LLM APIs may be slower and more error-prone than conventional, more deterministic APIs. You can use several Angular features to build a performant and user-friendly interface. + +* **Scoped Loading:** place the `resource` in the component that directly uses the data. This helps limit change detection cycles (especially in zoneless applications) and prevents blocking other parts of your application. If data needs to be shared across multiple components, provide the `resource` from a service. +* **SSR and Hydration:** use Server-Side Rendering (SSR) with incremental hydration to render the initial page content quickly. You can show a placeholder for the AI-generated content and defer fetching the data until the component hydrates on the client. +* **Loading State:** use the `resource` `LOADING` [status](guide/signals/resource#resource-status) to show an indicator, like a spinner, while the request is in flight. This status covers both initial loads and reloads. +* **Error Handling and Retries:** use the `resource` [**`reload()`**](guide/signals/resource#reloading) method as a simple way for users to retry failed requests, may be more prevalent when relying on AI generated content. + +The following example demonstrates how to create a responsive UI to dynamically display an AI generated image with loading and retry functionality. + +```angular-html + +@if (imgResource.isLoading()) { +
+ +
+ +} @else if (imgResource.hasValue()) { + + +} @else { +
+ +

Failed to load image. Click to retry.

+
+} +``` + + +## AI patterns in action: streaming chat responses +Interfaces often display partial results from LLM-based APIs incrementally as response data arrives. Angular's resource API provides the ability to stream responses to support this type of pattern. The `stream` property of `resource` accepts an asyncronous function you can use to apply updates to a signal value over time. The signal being updated represents the data being streamed. + +```ts +characters = resource({ + stream: async () => { + const data = signal>({value: ''}); + // Calls a Genkit streaming flow using the streamFlow method + // expose by the Genkit client SDK + const response = streamFlow({ + url: '/streamCharacters', + input: 10 + }); + + (async () => { + for await (const chunk of response.stream) { + data.update((prev) => { + if ('value' in prev) { + return { value: `${prev.value} ${chunk}` }; + } else { + return { error: chunk as unknown as Error }; + } + }); + } + })(); + + return data; + } +}); +``` + +The `characters` member is updated asynchronously and can be displayed in the template. + +```angular-html +@if (characters.isLoading()) { +

Loading...

+} @else if (characters.hasValue()) { +

{{characters.value()}}

+} @else { +

{{characters.error()}}

+} +``` + +On the server side, in `server.ts` for example, the defined endpoint sends the data to be streamed to the client. The following code uses Gemini with the Genkit framework but this technique is applicable to other APIs that support streaming responses from LLMs: + +```ts +import { startFlowServer } from '@genkit-ai/express'; +import { genkit } from "genkit/beta"; +import { googleAI, gemini20Flash } from "@genkit-ai/googleai"; + +const ai = genkit({ plugins: [googleAI()] }); + +export const streamCharacters = ai.defineFlow({ + name: 'streamCharacters', + inputSchema: z.number(), + outputSchema: z.string(), + streamSchema: z.string(), + }, + async (count, { sendChunk }) => { + const { response, stream } = ai.generateStream({ + model: gemini20Flash, + config: { + temperature: 1, + }, + prompt: `Generate ${count} different RPG game characters.`, + }); + + (async () => { + for await (const chunk of stream) { + sendChunk(chunk.content[0].text!); + } + })(); + + return (await response).text; +}); + +startFlowServer({ + flows: [streamCharacters], +}); + +``` diff --git a/adev-ja/src/content/ai/mcp-server-setup.en.md b/adev-ja/src/content/ai/mcp-server-setup.en.md index 504a28f7f2..2f114ec4f7 100644 --- a/adev-ja/src/content/ai/mcp-server-setup.en.md +++ b/adev-ja/src/content/ai/mcp-server-setup.en.md @@ -136,4 +136,4 @@ The Angular CLI MCP server provides several tools to assist you in your developm ## Feedback and New Ideas -The Angular team welcomes your feedback on the existing MCP capabilities and any ideas you have for new tools or features. Please share your thoughts by opening an issue on the [angular/angular GitHub repository](https://github.com/angular/angular/issues). \ No newline at end of file +The Angular team welcomes your feedback on the existing MCP capabilities and any ideas you have for new tools or features. Please share your thoughts by opening an issue on the [angular/angular GitHub repository](https://github.com/angular/angular/issues). diff --git a/adev-ja/src/content/ai/overview.en.md b/adev-ja/src/content/ai/overview.en.md index ca5bbdcf9e..39db0a91bb 100644 --- a/adev-ja/src/content/ai/overview.en.md +++ b/adev-ja/src/content/ai/overview.en.md @@ -60,60 +60,6 @@ The [Gemini API](https://ai.google.dev/gemini-api/docs) provides access to state * [AI Chatbot app template](https://github.com/FirebaseExtended/firebase-framework-tools/tree/main/starters/angular/ai-chatbot) - This template starts with a chatbot user interface that communicates with the Gemini API via HTTP. -## AI patterns in action: Streaming chat responses -Having text appear as the response is received from the model is a common UI pattern for web apps using AI. You can achieve this asynchronous task with Angular's `resource` API. The `stream` property of `resource` accepts an asynchronous function you can use to apply updates to a signal value over time. The signal being updated represents the data being streamed. - -```ts -characters = resource({ - stream: async () => { - const data = signal<{ value: string } | { error: unknown }>({ - value: "", - }); - - fetch(this.url).then(async (response) => { - if (!response.body) return; - - for await (const chunk of response.body) { - const chunkText = this.decoder.decode(chunk); - data.update((prev) => { - if ("value" in prev) { - return { value: `${prev.value} ${chunkText}` }; - } else { - return { error: chunkText }; - } - }); - } - }); - - return data; - }, - }); - -``` - -The `characters` member is updated asynchronously and can be displayed in the template. - -```html -

{{ characters.value() }}

-``` - -On the server side, in `server.ts` for example, the defined endpoint sends the data to be streamed to the client. The following code uses the Gemini API but this technique is applicable to other tools and frameworks that support streaming responses from LLMs: - -```ts - app.get("/api/stream-response", async (req, res) => { - ai.models.generateContentStream({ - model: "gemini-2.0-flash", - contents: "Explain how AI works", - }).then(async (response) => { - for await (const chunk of response) { - res.write(chunk.text); - } - }); - }); - -``` -This example connects to the Gemini API but other APIs that support streaming responses can be used here as well. [You can find the complete example on the Angular Github](https://github.com/angular/examples/tree/main/streaming-example). - ## Best Practices ### Connecting to model providers and keeping your API Credentials Secure When connecting to model providers, it is important to keep your API secrets safe. *Never put your API key in a file that ships to the client, such as `environments.ts`*. diff --git a/adev-ja/src/content/ai/overview.md b/adev-ja/src/content/ai/overview.md index 2bda085190..8ac6fbbdc6 100644 --- a/adev-ja/src/content/ai/overview.md +++ b/adev-ja/src/content/ai/overview.md @@ -60,60 +60,6 @@ Firebase AI LogicとAngularで構築する方法の例を次に示します。 * [AIチャットボットアプリテンプレート](https://github.com/FirebaseExtended/firebase-framework-tools/tree/main/starters/angular/ai-chatbot) - このテンプレートは、HTTP経由でGemini APIと通信するチャットボットユーザーインターフェースから始まります。 -## AIパターン実践: チャット応答のストリーミング {#ai-patterns-in-action-streaming-chat-responses} -モデルから応答が受信されるにつれてテキストが表示されるのは、AIを使用するWebアプリケーションで一般的なUIパターンです。この非同期タスクはAngularの`resource` APIで実現できます。`resource`の`stream`プロパティは、時間の経過とともにシグナル値に更新を適用するために使用できる非同期関数を受け入れます。更新されるシグナルは、ストリーミングされるデータを表します。 - -```ts -characters = resource({ - stream: async () => { - const data = signal<{ value: string } | { error: unknown }>({ - value: "", - }); - - fetch(this.url).then(async (response) => { - if (!response.body) return; - - for await (const chunk of response.body) { - const chunkText = this.decoder.decode(chunk); - data.update((prev) => { - if ("value" in prev) { - return { value: `${prev.value} ${chunkText}` }; - } else { - return { error: chunkText }; - } - }); - } - }); - - return data; - }, - }); - -``` - -`characters`メンバーは非同期で更新され、テンプレートに表示できます。 - -```html -

{{ characters.value() }}

-``` - -サーバー側では、例えば`server.ts`で、定義されたエンドポイントがクライアントにストリーミングされるデータを送信します。以下のコードはGemini APIを使用していますが、この手法はLLMからのストリーミング応答をサポートする他のツールやフレームワークにも適用可能です。 - -```ts - app.get("/api/stream-response", async (req, res) => { - ai.models.generateContentStream({ - model: "gemini-2.0-flash", - contents: "Explain how AI works", - }).then(async (response) => { - for await (const chunk of response) { - res.write(chunk.text); - } - }); - }); - -``` -この例はGemini APIに接続していますが、ストリーミング応答をサポートする他のAPIもここで使用できます。[完全な例はAngularのGithubで見つけることができます](https://github.com/angular/examples/tree/main/streaming-example)。 - ## ベストプラクティス ### モデルプロバイダーへの接続とAPI認証情報の保護 {#connecting-to-model-providers-and-keeping-your-api-credentials-secure} モデルプロバイダーに接続する際は、APIシークレットを安全に保つことが重要です。*APIキーを`environments.ts`のようなクライアントに配布されるファイルに決して含めないでください*。 diff --git a/adev-ja/src/content/guide/routing/data-resolvers.md b/adev-ja/src/content/guide/routing/data-resolvers.md index a9614a4c78..44075983b1 100644 --- a/adev-ja/src/content/guide/routing/data-resolvers.md +++ b/adev-ja/src/content/guide/routing/data-resolvers.md @@ -266,8 +266,10 @@ While data resolvers prevent loading states within components, they introduce a To improve user experience during resolver execution, you can listen to router events and show loading indicators: ```angular-ts -import { Component, inject, computed } from '@angular/core'; +import { Component, inject } from '@angular/core'; import { Router } from '@angular/router'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { map } from 'rxjs'; @Component({ selector: 'app-root', diff --git a/origin b/origin index 9e172e0280..65c5a734e2 160000 --- a/origin +++ b/origin @@ -1 +1 @@ -Subproject commit 9e172e0280549caf59d5b2025b2f09b7bae3477a +Subproject commit 65c5a734e2c11fe5d2fc4a1ef6dcf61d6ad1859a