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

Sunshine APIにAIのモデルを選択できるオプションを追加 #195

Merged
merged 5 commits into from
Aug 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: 1 addition & 3 deletions apps/api/src/features/guardians/guardian.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ import { UsageLogService } from '~/features/usageLogs/usageLog.service'
import { UsageFacade } from '~/features/usages/usage.facade'
import { UserPlanRepository } from '~/features/userPlans/userPlan.repository'
import { UserPlanService } from '~/features/userPlans/userPlan.service'
import { AnthropicClient } from '~/libs/anthropic'
import { GoogleClient } from '~/libs/google'
import { OpenAIClient } from '~/libs/openai'
import { AnthropicClient, GoogleClient, OpenAIClient } from '~/libs/models'
import { SupabaseClient } from '~/libs/supabase'

/**
Expand Down
26 changes: 10 additions & 16 deletions apps/api/src/features/guardians/guardian.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import { GoogleGenerativeAIProvider } from '@ai-sdk/google'
import { OpenAIProvider } from '@ai-sdk/openai'
import { InternalServerError } from '@peace-net/shared/core/error'
import { categoryScoresSchema } from '@peace-net/shared/schemas/guardian'
import type { CategoryScores, Models } from '@peace-net/shared/types/guardian'
import type { CategoryScores } from '@peace-net/shared/types/guardian'
import { Models } from '@peace-net/shared/types/model'
import { generateObject } from 'ai'
import { z } from 'zod'

import { selectAIModel } from '~/libs/models'

const systemPrompt = `
# 役割
あなたは日本語のコンテンツモデレーションの専門家です。
Expand Down Expand Up @@ -85,21 +88,12 @@ export class GuardianService implements IGuardianService {
selectedModel: Models,
): Promise<CategoryScores> {
try {
let model
switch (selectedModel) {
case 'gpt-4o-mini':
model = this.openai('gpt-4o-mini')
break
case 'claude-3-haiku':
model = this.anthropic('claude-3-haiku-20240307')
break
case 'gemini-1.5-flash':
model = this.google('models/gemini-1.5-flash')
break
default:
model = this.openai('gpt-4o-mini')
break
}
const model = selectAIModel(
selectedModel,
this.openai,
this.anthropic,
this.google,
)

const { object } = await generateObject({
model,
Expand Down
8 changes: 6 additions & 2 deletions apps/api/src/features/sunshines/sunshine.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { UsageLogService } from '~/features/usageLogs/usageLog.service'
import { UsageFacade } from '~/features/usages/usage.facade'
import { UserPlanRepository } from '~/features/userPlans/userPlan.repository'
import { UserPlanService } from '~/features/userPlans/userPlan.service'
import { OpenAIClient } from '~/libs/openai'
import { AnthropicClient, GoogleClient, OpenAIClient } from '~/libs/models'
import { SupabaseClient } from '~/libs/supabase'

/**
Expand All @@ -33,7 +33,11 @@ sunshineRoutes.post(
async (c) => {
return new SunshineController(
new SunshineUseCase(
new SunshineService(OpenAIClient(getEnv(c).OPENAI_API_KEY)),
new SunshineService(
OpenAIClient(getEnv(c).OPENAI_API_KEY),
AnthropicClient(getEnv(c).ANTHROPIC_API_KEY),
GoogleClient(getEnv(c).GOOGLE_API_KEY),
),
new UsageFacade(
new UserPlanService(
new UserPlanRepository(
Expand Down
29 changes: 24 additions & 5 deletions apps/api/src/features/sunshines/sunshine.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { AnthropicProvider } from '@ai-sdk/anthropic'
import { GoogleGenerativeAIProvider } from '@ai-sdk/google'
import { OpenAIProvider } from '@ai-sdk/openai'
import { InternalServerError } from '@peace-net/shared/core/error'
import { Models } from '@peace-net/shared/types/model'
import { SunshineResult } from '@peace-net/shared/types/sunshine'
import { generateObject } from 'ai'
import { z } from 'zod'

import { selectAIModel } from '~/libs/models'

const systemPrompt = `
あなたは、ネガティブな表現をポジティブで建設的な表現に変換する専門家です。以下の指針に従ってテキストを変換してください:

Expand Down Expand Up @@ -33,16 +38,30 @@ const systemPrompt = `
変換したテキストは、'text'オブジェクトに格納してください。
`
export interface ISunshineService {
sunshineText(text: string): Promise<SunshineResult>
sunshineText(text: string, selectedModel: Models): Promise<SunshineResult>
}

export class SunshineService implements ISunshineService {
constructor(private openai: OpenAIProvider) {}
constructor(
private openai: OpenAIProvider,
private anthropic: AnthropicProvider,
private google: GoogleGenerativeAIProvider,
) {}

async sunshineText(text: string): Promise<SunshineResult> {
async sunshineText(
text: string,
selectedModel: Models,
): Promise<SunshineResult> {
try {
const model = selectAIModel(
selectedModel,
this.openai,
this.anthropic,
this.google,
)

const { object } = await generateObject({
model: this.openai('gpt-4o-mini'),
model,
schema: z.object({ text: z.string() }),
messages: [
{ role: 'system', content: systemPrompt },
Expand All @@ -53,7 +72,7 @@ export class SunshineService implements ISunshineService {
return object
} catch (error) {
console.error(error)
throw new InternalServerError('Failed to generate object')
throw new InternalServerError('Failed to generate text')
}
}
}
4 changes: 2 additions & 2 deletions apps/api/src/features/sunshines/sunshine.usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export class SunshineUseCase implements ISunshineUseCase {
input: SunshineTextInput,
): Promise<Result<SunshineResult>> {
try {
const { text, userId, apiKeyId } = input
const result = await this.SunshineService.sunshineText(text)
const { text, model, userId, apiKeyId } = input
const result = await this.SunshineService.sunshineText(text, model)

await this.usageFacade.incrementUsage(userId, apiKeyId, 'sunshines')

Expand Down
13 changes: 0 additions & 13 deletions apps/api/src/libs/anthropic.ts

This file was deleted.

13 changes: 0 additions & 13 deletions apps/api/src/libs/google.ts

This file was deleted.

62 changes: 62 additions & 0 deletions apps/api/src/libs/models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { AnthropicProvider, createAnthropic } from '@ai-sdk/anthropic'
import {
createGoogleGenerativeAI,
GoogleGenerativeAIProvider,
} from '@ai-sdk/google'
import { createOpenAI, OpenAIProvider } from '@ai-sdk/openai'
import { Models } from '@peace-net/shared/types/model'
import { LanguageModel } from 'ai'

/**
* OpenAI APIのクライアントを生成します
*
* @param apiKey - OpenAI APIのAPIキー
* @returns OpenAI APIのクライアント
*/
export const OpenAIClient = (apiKey: string) => {
return createOpenAI({
apiKey,
})
}

/**
* Google Generative AI APIのクライアントを生成します
*
* @param apiKey - Google Generative AI APIのAPIキー
* @returns Google Generative AIのクライアント
*/
export const GoogleClient = (apiKey: string) => {
return createGoogleGenerativeAI({
apiKey,
})
}

/**
* Anthropic APIのクライアントを生成します
*
* @param apiKey - Anthropic APIのAPIキー
* @returns Anthropic APIのクライアント
*/
export const AnthropicClient = (apiKey: string) => {
return createAnthropic({
apiKey,
})
}

export const selectAIModel: (
selectedModel: Models,
openai: OpenAIProvider,
anthropic: AnthropicProvider,
google: GoogleGenerativeAIProvider,
) => LanguageModel = (selectedModel, openai, anthropic, google) => {
switch (selectedModel) {
case 'gpt-4o-mini':
return openai('gpt-4o-mini')
case 'claude-3-haiku':
return anthropic('claude-3-haiku-20240307')
case 'gemini-1.5-flash':
return google('models/gemini-1.5-flash')
default:
return openai('gpt-4o-mini')
}
}
13 changes: 0 additions & 13 deletions apps/api/src/libs/openai.ts

This file was deleted.

2 changes: 1 addition & 1 deletion apps/docs/docs/features/guardian.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ default値は`0.5`です。

**`model`** string optional <br/>
指定可能なモデル
- gpt-4o-mini
- gpt-4o-mini (default)
- claude-3-haiku
- gemini-1.5-flash

Expand Down
6 changes: 6 additions & 0 deletions apps/docs/docs/features/sunshine.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export const SunshineApiName = () => {
**`text`** string **required** <br/>
最大500文字までを受け付けています。

**`model`** string optional <br/>
指定可能なモデル
- gpt-4o-mini (default)
- claude-3-haiku
- gemini-1.5-flash

### リクエスト例
<details>
<summary>cURL</summary>
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/docusaurus.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const config: Config = {
lastVersion: 'current',
versions: {
current: {
label: '1.4.1 (latest)',
label: '1.5.0 (latest)',
path: '/',
},
},
Expand Down
66 changes: 66 additions & 0 deletions apps/docs/versioned_docs/version-1.4.1/code-reference/golang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Go

```go
// main.go
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)

var (
apiKey = "YOUR_API_KEY"
apiUrl = "https://api.peeace.net/v1/guardians/text"
)

func main() {
// リクエストを作成
body, err := json.Marshal(map[string]string{
"text": "最低な文章",
})
if err != nil {
fmt.Println("Error marshalling request body:", err)
return
}

req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(body))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))

// リクエスト
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()

// レスポンスをチェック
if resp.StatusCode != http.StatusOK {
fmt.Println("Request failed with status:", resp.Status)
return
}

var responseBody map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&responseBody); err != nil {
fmt.Println("Error decoding response body:", err)
return
}

fmt.Println("Response:", responseBody)
}
```

### 実行

```sh
go run main.go
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# コードリファレンス

<!-- <言語名>がタイトルだと望ましい -->
- [Node.js](./node-js.md)
- [Go](./golang.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Node.js

```js
// 変数をセット
//// YOUR_API_KEYを取得したものに変更してください
const apiKey= 'YOUR_API_KEY';

const apiUrl = "https://api.peeace.net/v1/guardians/text";
const requestBody = {
text: "最低な文章"
};

fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(requestBody)
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});

```
Loading
Loading