@Schema() abstractclass $CheckAvailabilityInput{ @Field(description: 'The restaurant name, e.g. Cymbal Bistro.') Stringget restaurant;
@Field(description: 'The date for the reservation, e.g. tonight, tomorrow, or YYYY-MM-DD.') Stringget date;
@Field(description: 'Number of guests.') intget partySize; }
@Schema() abstractclass $CheckAvailabilityOutput{ Stringget restaurant; Stringget date; intget partySize; boolget available; List<String> get availableSlots; List<String> get seatingAreas; }
// ConfirmReservationInput, ConfirmReservationOutput, and _resolveIsoDate omitted for brevity.
// Register plugins on the shared Genkit instance final Genkit ai = Genkit(plugins: [googleAI(), A2uiPlugin()]);
// Tool 1: Check table availability and open time slots final checkAvailability = ai.defineTool( name: 'checkAvailability', description: 'Checks table availability, open time slots, and seating areas for a restaurant.', inputSchema: CheckAvailabilityInput.$schema, outputSchema: CheckAvailabilityOutput.$schema, fn: (input, _) async { return .response( CheckAvailabilityOutput( restaurant: input.restaurant.isEmpty ? 'Cymbal Bistro' : input.restaurant, date: _resolveIsoDate(input.date), partySize: input.partySize, available: true, availableSlots: const ['6:00 PM', '6:30 PM', '7:00 PM', '7:30 PM', '8:00 PM'], seatingAreas: const ['Indoor Dining', 'Heated Patio', 'Chef\'s Counter'], ), ); }, );
// Tool 2: Confirm a reservation and issue a confirmation code final confirmReservation = ai.defineTool( name: 'confirmReservation', description: 'Books and confirms a dining reservation, returning a confirmation code.', inputSchema: ConfirmReservationInput.$schema, outputSchema: ConfirmReservationOutput.$schema, fn: (input, _) async { final resolvedDate = _resolveIsoDate(input.date); final seed = (resolvedDate.hashCode ^ input.time.hashCode ^ input.partySize).abs(); return .response( ConfirmReservationOutput( confirmationCode: 'CB-${1000 + (seed % 9000)}', restaurant: input.restaurant.isEmpty ? 'Cymbal Bistro' : input.restaurant, date: resolvedDate, time: input.time, partySize: input.partySize, seatingArea: input.seatingArea ?? 'Indoor Dining', specialRequests: input.specialRequests ?? 'None', status: 'Confirmed', ), ); }, );
// Define the stateful agent with the a2ui middleware attached final uiAgent = ai.defineAgent( name: 'uiAgent', model: googleAI.gemini('gemini-4-hydrogen'), system: 'You are the dining concierge for Cymbal Bistro. Keep text responses brief.\n' 'Use checkAvailability before rendering a reservation card, and use ' 'confirmReservation when the user submits their booking to replace the ' 'same surface with a ConfirmationPass card showing their confirmation code.', tools: [checkAvailability, confirmReservation], use: [a2ui(catalog: bistroCatalogId, validate: 'warn')], store: InMemorySessionStore(), );
在這裡,bistroCatalogId 指向在 擴展元件目錄 中定義的自訂目錄。如果您只需要 18 個內建元件,請省略 catalog 參數。對於 Google Cloud 部署,將 googleAI 替換為 Vertex AI plugin 並呼叫 vertexAI.gemini('gemini-4-hydrogen')。
@override void initState() { super.initState(); // Track each created surface by surface.id; replacements with the same id // update in place rather than appending a duplicate card. _processor.model.onSurfaceCreated.subscribe((surface) { if (!mounted) return; if (!_surfaceIds.contains(surface.id)) { setState(() => _surfaceIds.add(surface.id)); } else { setState(() {}); } }); _processor.model.onSurfaceDeleted.subscribe((_) { if (mounted) setState(() {}); }); }
Future<void> _runTurn(AgentTurn turn) async { awaitfor (final chunk in turn.stream) { // 1. Append streamed prose text deltas if (chunk.text.isNotEmpty) { _appendProseDelta(chunk.text); }
// 2. Feed streamed A2UI messages into the MessageProcessor for (final m in a2uiMessagesFrom(chunk.raw.modelChunk?.content)) { try { _processor.processMessages([m]); } onObjectcatch (err) { debugPrint('Failed to apply A2UI message: $err'); } } } await turn.response; }
感謝所有套件作者、貢獻者和早期存取計畫參與者,特別是 Jon Holtan、Rody Davis、Dominik Roszkowski、Alexander Thiele 和 Morgan McKenzie。這些社群成員測試了早期版本、審查了文件並幫助塑造了這些 API。請持續關注有關直接原生互通的專門文章。
在 Windows 和 Linux 上,桌面渲染獲得了關鍵的保真度和效能升級。Windows 引擎現在預設請求 OpenGL ES 3,同時保留自動 OpenGL ES 2 回退支援,解鎖了現代圖形功能,而不會丟棄舊的 PC。Windows 應用程式現在可以從包含非 ASCII 字元的路徑(例如國際使用者名稱或資料夾名稱)載入資產和檔案。Windows 還以改進的對比度渲染更清晰的文字,並跳過每個畫面額外的全螢幕複製以減少 GPU 開銷。在 Windows 和 Linux 上,改進的抗鋸齒平滑了分層 UI 元素和自訂形狀上的鋸齒邊緣。
@Schema() abstractclass $TripRequest{ Stringget destination; intget days; } // ...plus an Itinerary schema for the result. final ai = Genkit(plugins: [googleAI()]);
final planTrip = ai.defineFlow( name: 'planTrip', inputSchema: TripRequest.$schema, outputSchema: Itinerary.$schema, fn: (request, _) async { final response = await ai.generate( model: googleAI.gemini('gemini-flash-latest'), prompt: 'Plan a ${request.days}-day trip to ${request.destination}.', outputSchema: Itinerary.$schema, ); return response.output!; }, );
await (GenkitRouter()..addAction(planTrip)).serve(port: 8080); // POST /planTrip
// shared/lib/models.dart (used by both server and app) @Schema() abstractclass $TripRequest{ Stringget destination; intget days; } // ...plus an Itinerary schema for the result.
// server/bin/server.dart final planTrip = ai.defineFlow( name: 'planTrip', inputSchema: TripRequest.$schema, outputSchema: Itinerary.$schema, fn: (request, _) async { final response = await ai.generate( model: googleAI.gemini('gemini-flash-latest'), prompt: 'Plan a ${request.days}-day trip to ${request.destination}.', outputSchema: Itinerary.$schema, ); return response.output!; }, ); await (GenkitRouter()..addAction(planTrip)).serve(port: 8080); // POST /planTrip
// app/lib/main.dart final planTrip = defineRemoteAction( url: 'https://api.example.com/planTrip', // Your Genkit endpoint inputSchema: TripRequest.$schema, outputSchema: Itinerary.$schema, ); final itinerary = await planTrip( input: TripRequest(destination: 'Kyoto', days: 5), );
Dart 執行到哪裡,程式碼就執行到哪裡
因為您的 AI 邏輯是用標準 Dart 撰寫的,所以您可以透過熱重載快速疊代,並靈活地在適合您架構的任何地方執行程式碼:
直接在 Flutter 中:直接從您的應用程式呼叫模型,進行快速原型開發或自帶金鑰體驗(切勿在已發佈的用戶端應用程式中嵌入私有 API 金鑰)。
// server/bin/server.dart final genkit = GenkitRouter() ..addAction( googleAI().model('gemini-flash-latest'), path: '/gemini', // Runs before the model; throw a GenkitException to reject the request. contextProvider: (request) async => {'user': await verifyUser(request.headers['authorization'])}, ); await genkit.serve(port: 8080);
// app/lib/main.dart final ai = Genkit(); final gemini = ai.defineRemoteModel( name: 'gemini', url: 'https://api.example.com/gemini', headers: (context) async => {'Authorization': 'Bearer ${await getIdToken()}'}, ); final response = await ai.generate( model: gemini, prompt: 'Suggest a packing list for Kyoto in April.', );
final bookHotel = ai.defineTool( name: 'bookHotel', description: 'Books a hotel room for the user.', inputSchema: HotelBooking.$schema, fn: (input, ctx) async { // Ask the user to confirm before charging their card. if (ctx.resumed == null) { return .interrupt({'hotel': input.hotelName, 'total': input.totalPrice}); } final confirmation = await hotels.book(input); return .response(confirmation.id); }, );
--- model: googleai/gemini-flash-latest input: schema: destination: string --- Write a friendly, two-sentence introduction to {{destination}} for a first-time visitor.
1 2
final introPrompt = await ai.prompt('destinationIntro'); final response = await introPrompt({'destination': 'Kyoto'});
final travelAgent = ai.defineAgent( name: 'travelAgent', model: googleAI.gemini('gemini-flash-latest'), system: 'You help users plan and book trips.', tools: [searchFlights, bookHotel], store: FirestoreSessionStore(collection: 'sessions'), );
final chat = travelAgent.chat(sessionId: 'user-123'); final response = await chat.send(text: 'Find me a weekend in Lisbon.');
@freezed sealedclassMessageParameterswith_$MessageParameters{ /// Creates a new latte order. @Implements.fromString('BackendMessage<SaveOrderResponse>') constfactory MessageParameters.saveOrder({ @LatteOrderConverter() required LatteOrder order, }) = SaveOrderParameters;
/// Marks a latte order as completed. @Implements.fromString('BackendMessage<EmptyResponse>') constfactory MessageParameters.completeOrder({ requiredString orderId, requiredString baristaId, }) = CompleteOrderParameters;
// Many more message types... }
MessageResponse
這關閉了迴圈,宣告了每個方法呼叫預期的回應類別。它為需要即時回饋的方法提供了單獨的回應類型,並提供了空回應以表示 202 Accepted 或 204 No Content HTTP 回應。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
@freezed sealedclassMessageResponsewith_$MessageResponse{ /// Return data for [SaveOrderParameters]. constfactory MessageResponse.saveOrder({required LatteOrder? latteOrder}) = SaveOrderResponse;
// Many more response types...
/// Placeholder for method calls which require no return value. /// /// This is typically because the client will pick up any state changes via /// watched Firestore collections. constfactory MessageResponse.empty() = EmptyResponse; }