Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/refactor #12

Merged
merged 7 commits into from
Oct 20, 2024
Merged
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
4 changes: 0 additions & 4 deletions functions/src/genkit-functions/analyzeStorageImage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import * as genkitFunctions from '@genkit-ai/firebase/functions'
import * as z from 'zod'
import { analyzeStorageInputSchema } from '../schemas/analyzeStorageInputSchema'
import { analyzeStorageOutputSchema } from '../schemas/analyzeStorageOutputSchema'
import { isGenkitEnabled } from '../utils/genkitUtils'

// Cloud Storage からファイルを読み込み、Gemini Flash 1.5 で要約する関数
export const analyzeStorageImage = genkitFunctions.onFlow(
{
name: `analyzeStorageImage`,
Expand All @@ -17,8 +15,6 @@ export const analyzeStorageImage = genkitFunctions.onFlow(
authPolicy: genkitFunctions.noAuth(),
},
async (input) => {
if (!(await isGenkitEnabled())) throw new Error(`Genkit が無効になっています。`)

const analyzeFilePrompt = await prompt<z.infer<typeof analyzeStorageInputSchema>>(`analyze`)
const result = await analyzeFilePrompt.generate({ input })

Expand Down
2 changes: 1 addition & 1 deletion functions/src/genkit-functions/analyzeWebContents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const analyzeWebContents = genkitFunctions.onFlow(
async (input) => {
const result = await generate({
model: gemini15Flash,
prompt: `以下のウェブページの内容を分析してください。:${input}`,
prompt: `Analyze the content of the following webpage: ${input}`,
tools: [webLoader],
output: {
format: `text`,
Expand Down
12 changes: 3 additions & 9 deletions functions/src/genkit-functions/anonymousFirestoreChatbot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as config from '../config/firebase'
import { db } from '../config/firebase'
import { chatbotInputSchema } from '../schemas/chatbotInputSchema'
import { chatbotOutputSchema } from '../schemas/chatbotOutputSchema'
import { createChatbotInput, isGenkitEnabled } from '../utils/genkitUtils'
import { createChatbotInput } from '../utils/genkitUtils'

export const anonymousFirestoreChatbot = genkitFunctions.onFlow(
{
Expand All @@ -15,21 +15,15 @@ export const anonymousFirestoreChatbot = genkitFunctions.onFlow(
cors: true,
secrets: [config.googleAIapiKey],
},
inputSchema: z.object({
userId: z.string(),
chatId: z.string(),
currentQuery: z.string(),
}),
inputSchema: chatbotInputSchema,
outputSchema: chatbotOutputSchema,
authPolicy: firebaseAuth((user) => {
if (user.firebase?.sign_in_provider !== `anonymous`) {
throw new Error(`匿名認証されたユーザーのみがアクセスできます`)
throw new Error(`Only anonymously authenticated users can access this function`)
}
}),
},
async (input) => {
if (!(await isGenkitEnabled())) throw new Error(`Genkit が無効になっています。`)

const userDoc = await db.collection(`users`).doc(input.userId).get()
const userData = userDoc.data()

Expand Down
3 changes: 0 additions & 3 deletions functions/src/genkit-functions/generateImage.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { prompt } from '@genkit-ai/dotprompt'
import * as genkitFunctions from '@genkit-ai/firebase/functions'
import * as z from 'zod'
import { googleAIapiKey } from '../config/firebase'
import { generateImageInputSchema } from '../schemas/generateImageInputSchema'

// 画像出力の Genkit Functions
export const generateImage = genkitFunctions.onFlow(
{
name: `generateImage`,
httpsOptions: {
cors: true,
secrets: [googleAIapiKey],
},
inputSchema: generateImageInputSchema,
authPolicy: genkitFunctions.noAuth(),
Expand Down
11 changes: 5 additions & 6 deletions functions/src/genkit-functions/noAuthFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { prompt } from '@genkit-ai/dotprompt'
import * as genkitFunctions from '@genkit-ai/firebase/functions'
import * as z from 'zod'
import * as config from '../config/firebase'
import { chatbotInputSchema } from '../schemas/chatbotInputSchema'
import { chatbotOutputSchema } from '../schemas/chatbotOutputSchema'
import { noAuthInputSchema } from '../schemas/noAuthInputSchema'
import { noAuthOutputSchema } from '../schemas/noAuthOutputSchema'

// 認証なしの Genkit Functions
export const noAuthFunction = genkitFunctions.onFlow(
{
name: `noAuthFunction`,
Expand All @@ -14,11 +13,11 @@ export const noAuthFunction = genkitFunctions.onFlow(
secrets: [config.googleAIapiKey],
},
authPolicy: genkitFunctions.noAuth(),
inputSchema: chatbotInputSchema,
outputSchema: chatbotOutputSchema,
inputSchema: noAuthInputSchema,
outputSchema: noAuthOutputSchema,
},
async (input) => {
const chatbotPrompt = await prompt<z.infer<typeof chatbotInputSchema>>(`chatbot`)
const chatbotPrompt = await prompt<z.infer<typeof noAuthInputSchema>>(`chatbot`)
const result = await chatbotPrompt.generate({ input })
return result.output()
}
Expand Down
21 changes: 1 addition & 20 deletions functions/src/schemas/chatbotInputSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,6 @@ import * as z from 'zod'

export const chatbotInputSchema = z.object({
userId: z.string(),
chatId: z.string(),
currentQuery: z.string(),
chatHistory: z.array(
z.object({
role: z.enum([`user`, `assistant`]),
content: z.string(),
timestamp: z.string(),
})
),
userProfile: z.object({
name: z.string(),
preferredLanguage: z.string(),
accountType: z.string(),
}),
productCatalog: z.array(
z.object({
id: z.string(),
name: z.string(),
details: z.string(),
price: z.number(),
})
),
})
26 changes: 26 additions & 0 deletions functions/src/schemas/noAuthInputSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as z from 'zod'

export const noAuthInputSchema = z.object({
userId: z.string(),
currentQuery: z.string(),
chatHistory: z.array(
z.object({
role: z.enum([`user`, `assistant`]),
content: z.string(),
timestamp: z.string(),
})
),
userProfile: z.object({
name: z.string(),
preferredLanguage: z.string(),
accountType: z.string(),
}),
productCatalog: z.array(
z.object({
id: z.string(),
name: z.string(),
details: z.string(),
price: z.number(),
})
),
})
7 changes: 7 additions & 0 deletions functions/src/schemas/noAuthOutputSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * as z from 'zod'

export const noAuthOutputSchema = z.object({
response: z.string(),
suggestedActions: z.array(z.string()),
sentiment: z.enum([`positive`, `neutral`, `negative`]),
})
8 changes: 1 addition & 7 deletions functions/src/utils/genkitUtils.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { defineTool } from '@genkit-ai/ai'
import * as cheerio from 'cheerio'
import * as z from 'zod'
import { db } from '../config/firebase'
import { chatbotInputSchema } from '../schemas/chatbotInputSchema'

export async function isGenkitEnabled(): Promise<boolean> {
const appConfDoc = await db.collection(`appConf`).doc(`config`).get()
return appConfDoc.data()?.genkitEnabled ?? false
}

export const webLoader = defineTool(
{
name: `webLoader`,
description: `指定されたURLにアクセスし、ウェブページの内容を取得します。`,
description: `Accesses the specified URL and retrieves the content of the webpage.`,
inputSchema: z.object({ url: z.string().url() }),
outputSchema: z.string(),
},
Expand All @@ -31,15 +25,15 @@
export function createChatbotInput(
userId: string,
currentQuery: string,
userData: any,

Check warning on line 28 in functions/src/utils/genkitUtils.ts

View workflow job for this annotation

GitHub Actions / Cloud Run Functions CI

Unexpected any. Specify a different type
chatData: any,

Check warning on line 29 in functions/src/utils/genkitUtils.ts

View workflow job for this annotation

GitHub Actions / Cloud Run Functions CI

Unexpected any. Specify a different type
productData: any

Check warning on line 30 in functions/src/utils/genkitUtils.ts

View workflow job for this annotation

GitHub Actions / Cloud Run Functions CI

Unexpected any. Specify a different type
): z.infer<typeof chatbotInputSchema> {
return {
userId,
currentQuery,
chatHistory:
chatData?.messages?.map((message: any) => ({

Check warning on line 36 in functions/src/utils/genkitUtils.ts

View workflow job for this annotation

GitHub Actions / Cloud Run Functions CI

Unexpected any. Specify a different type
role: message.role as `user` | `assistant`,
content: message.content,
timestamp: message.timestamp,
Expand Down
6 changes: 3 additions & 3 deletions terraform/authentication.tf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Firebase Authentication のプロビジョニング
# Provisioning Firebase Authentication
resource "google_identity_platform_config" "default" {
provider = google-beta
project = var.project_id
Expand All @@ -7,8 +7,8 @@ resource "google_identity_platform_config" "default" {
]
}

# Firebase Authentication が依存する Identity Platform のプロビジョニング
# 今回は匿名認証のみ有効化
# Provisioning Identity Platform which Firebase Authentication depends on
# Only anonymous authentication is enabled for this configuration
resource "google_identity_platform_project_default_config" "default" {
provider = google-beta
project = var.project_id
Expand Down
2 changes: 1 addition & 1 deletion terraform/backend.tf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Terraform のバックエンドを GCS に設定
# Configure Terraform backend to use Google Cloud Storage (GCS)
terraform {
backend "gcs" {
bucket = "backend"
Expand Down
29 changes: 14 additions & 15 deletions terraform/firestore.tf
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Firestore のマスタデータ管理 (アプリケーション設定と Genkit 参照用のサンプルデータ)
# Firestore master data management (Application settings and sample data for Genkit reference)
locals {
docs = [
# アプリケーション設定
# 今回は、Genkit を意図しない使用を防ぐために有効無効フラグを用意している
# Application settings
{
collection = "appConf"
document_id = "config"
Expand All @@ -11,8 +10,8 @@ locals {
})
},

# チャットボットを使用するダミーユーザー
# functions/src/genkit-functions が実際に参照する Firestore データ
# Dummy users for chatbot interaction
# Firestore data actually referenced by functions/src/genkit-functions
{
collection = "users"
document_id = "user123"
Expand Down Expand Up @@ -44,7 +43,7 @@ locals {
})
},

# ユーザーのチャット履歴
# User chat history
{
collection = "users/user123/chatHistory"
document_id = "chat123"
Expand Down Expand Up @@ -108,7 +107,7 @@ locals {
})
},

# 商品マスタ
# Product catalog
{
collection = "productCatalog"
document_id = "tablet_1"
Expand All @@ -121,7 +120,7 @@ locals {
]
}

# Firestore データベースのプロビジョニング
# Provisioning Firestore database
resource "google_firestore_database" "firestore" {
provider = google-beta
project = var.project_id
Expand All @@ -130,13 +129,13 @@ resource "google_firestore_database" "firestore" {
type = "FIRESTORE_NATIVE"
concurrency_mode = "OPTIMISTIC"

# Firebase Google Cloud プロジェクトで有効になる前に Firestore を初期化する前に待つ
# Wait for Firebase to be enabled in the Google Cloud project before initializing Firestore
depends_on = [
google_firebase_project.default,
]
}

# Firestore のセキュリティルールをローカルファイルから作成
# Create Firestore security rules from local file
resource "google_firebaserules_ruleset" "firestore" {
provider = google-beta
project = var.project_id
Expand All @@ -151,26 +150,26 @@ resource "google_firebaserules_ruleset" "firestore" {
create_before_destroy = true
}

# Firestore がプロビジョニングされる前にこのルールセットを作成する前に待つ
# Wait for Firestore to be provisioned before creating this ruleset
depends_on = [
google_firestore_database.firestore,
]
}

# Firestore インスタンスのルールセットを解放
# Release ruleset for Firestore instance
resource "google_firebaserules_release" "firestore" {
provider = google-beta
name = "cloud.firestore"
ruleset_name = google_firebaserules_ruleset.firestore.name
project = var.project_id

# Firestore がプロビジョニングされる前にこのルールセットを解放する前に待つ
# Wait for Firestore to be provisioned before releasing this ruleset
depends_on = [
google_firestore_database.firestore,
]
}

# Firestore にマスタデータを追加
# Add master data to Firestore
resource "google_firestore_document" "docs" {
for_each = { for doc in local.docs : doc.document_id => doc }
provider = google-beta
Expand All @@ -185,7 +184,7 @@ resource "google_firestore_document" "docs" {
}

# Firebase Firestore Index
# 今後書くコレクションのインデックスを定義する場合はコメントアウトを外して適宜編集してください
# To define indexes for future collections, uncomment and edit as needed
# resource "google_firestore_index" "user-index" {
# project = var.project_id
# collection = "user"
Expand Down
6 changes: 3 additions & 3 deletions terraform/main.tf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 必要な API を有効化
# Enable necessary APIs
resource "google_project_service" "default" {
provider = google-beta.no_user_project_override
project = var.project_id
Expand All @@ -17,12 +17,12 @@ resource "google_project_service" "default" {
disable_on_destroy = false
}

# 上記で作成した新しいプロジェクトに Firebase サービスを有効化
# Enable Firebase services for the newly created project above
resource "google_firebase_project" "default" {
provider = google-beta
project = var.project_id

# 必要な API が有効化されるまで待つ
# Wait for the necessary APIs to be enabled
depends_on = [
google_project_service.default
]
Expand Down
8 changes: 4 additions & 4 deletions terraform/provider.tf
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Terraform のプロバイダをバージョンごとに設定
# Configure Terraform providers with specific versions
terraform {
required_providers {
google-beta = {
Expand All @@ -8,14 +8,14 @@ terraform {
}
}

# プロバイダを設定して、リソースブロックで指定されたプロジェクトを使用してクォータチェックを行う
# Configure provider to perform quota checks using the project specified in resource blocks
provider "google-beta" {
user_project_override = true
billing_project = var.project_id
}

# プロバイダを設定して、リソースブロックで指定されたプロジェクトを使用してクォータチェックを行わない
# このプロバイダはプロジェクト作成時とサービス初期化時にのみ使用する
# Configure provider to not perform quota checks using the project specified in resource blocks
# This provider is used only for project creation and service initialization
provider "google-beta" {
alias = "no_user_project_override"
user_project_override = false
Expand Down
Loading
Loading