diff --git a/package-lock.json b/package-lock.json index ac62d7d..3359fc3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "tdnet-digest", - "version": "0.1.0", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "tdnet-digest", - "version": "0.1.0", + "version": "0.4.0", "dependencies": { "pdfjs-dist": "^5.4.394", "react": "^18.3.1", @@ -31,7 +31,7 @@ "vite": "^6.0.3" }, "engines": { - "node": ">=18.0.0" + "node": ">=20.0.0" } }, "node_modules/@babel/code-frame": { diff --git a/src/background/index.ts b/src/background/index.ts index 376c62a..91bf3e2 100644 --- a/src/background/index.ts +++ b/src/background/index.ts @@ -1,6 +1,7 @@ import { generateText, type LLMConfig, type ChatMessage } from '@/lib/llm-client'; import { detectDocumentType, detectEarningsContext, type DocumentType } from '@/lib/document-type'; -import { getPromptForDocumentType } from '@/lib/prompts'; +import { getPromptForDocumentType, getExtractionPrompt } from '@/lib/prompts'; +import { getFormatPrompt } from '@/lib/format-prompts'; import type { SummaryMetadata, ExtractionMode } from '@/types/summaryMetadata'; interface SummarizeRequest { @@ -16,6 +17,7 @@ interface Settings { model: string; customUrl?: string; extractionMode?: ExtractionMode; + twoPassMode?: boolean; } // 拡張機能のインストール・更新時 @@ -121,7 +123,7 @@ async function handleSummarize( async function getSettings(): Promise { return new Promise((resolve) => { chrome.storage.sync.get( - ['provider', 'apiKey', 'model', 'customUrl', 'extractionMode'], + ['provider', 'apiKey', 'model', 'customUrl', 'extractionMode', 'twoPassMode'], (result) => { resolve({ provider: result.provider || 'openai', @@ -129,6 +131,7 @@ async function getSettings(): Promise { model: result.model || 'gpt-4o', customUrl: result.customUrl || '', extractionMode: result.extractionMode || 'full', + twoPassMode: result.twoPassMode !== undefined ? result.twoPassMode : true, }); } ); @@ -150,6 +153,27 @@ async function fetchPDF(url: string): Promise { } } +/** + * LLMレスポンスからJSONを解析する(フォールバック付き) + */ +function tryParseJson(text: string): unknown | null { + // コードブロック内のJSONを抽出 + const codeBlockMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/); + const jsonStr = codeBlockMatch ? codeBlockMatch[1].trim() : text.trim(); + + try { + return JSON.parse(jsonStr); + } catch { + // 先頭/末尾の非JSON文字を除去して再試行 + const cleaned = jsonStr.replace(/^[^{[]*/, '').replace(/[^}\]]*$/, ''); + try { + return JSON.parse(cleaned); + } catch { + return null; + } + } +} + async function summarizeWithLLM( pdfData: ArrayBuffer, settings: Settings, @@ -194,26 +218,82 @@ async function summarizeWithLLM( baseUrl: settings.customUrl || undefined, }; - // 文書タイプ別プロンプトを使用 + // 文書タイプ別コンテキスト const earningsContext = documentType === 'earnings' ? detectEarningsContext(title) : undefined; - const { system, user } = getPromptForDocumentType(documentType, pdfText, earningsContext); - - // メッセージを構築 - const messages: ChatMessage[] = [ - { role: 'system', content: system }, - { role: 'user', content: user }, - ]; - // 統一LLMクライアントを使用して要約を生成 - const summary = await generateText(llmConfig, messages); + // 2パスモード判定(デフォルトON) + const useTwoPass = settings.twoPassMode !== false; - return { summary, metadata }; + if (useTwoPass) { + return await summarizeTwoPass(llmConfig, documentType, pdfText, earningsContext, metadata); + } else { + return await summarizeOnePass(llmConfig, documentType, pdfText, earningsContext, metadata); + } } catch (error) { console.error('[Background] LLM要約エラー:', error); throw error; } } +/** + * 1パス要約(従来方式) + */ +async function summarizeOnePass( + llmConfig: LLMConfig, + documentType: DocumentType, + pdfText: string, + earningsContext: ReturnType | undefined, + metadata: SummaryMetadata +): Promise<{ summary: string; metadata: SummaryMetadata }> { + const { system, user } = getPromptForDocumentType(documentType, pdfText, earningsContext); + const messages: ChatMessage[] = [ + { role: 'system', content: system }, + { role: 'user', content: user }, + ]; + const summary = await generateText(llmConfig, messages); + return { summary, metadata }; +} + +/** + * 2パス要約(情報抽出→フォーマット整形) + */ +async function summarizeTwoPass( + llmConfig: LLMConfig, + documentType: DocumentType, + pdfText: string, + earningsContext: ReturnType | undefined, + metadata: SummaryMetadata +): Promise<{ summary: string; metadata: SummaryMetadata }> { + // パス1: 情報抽出(JSON) + console.log('[Background] 2パス要約: パス1(情報抽出)開始'); + const { system: s1, user: u1 } = getExtractionPrompt(documentType, pdfText, earningsContext); + const extractedText = await generateText(llmConfig, [ + { role: 'system', content: s1 }, + { role: 'user', content: u1 }, + ]); + + // JSON解析 + const parsed = tryParseJson(extractedText); + if (!parsed) { + // JSON解析失敗 → パス1の出力をそのまま返す(1パスフォールバック) + console.warn('[Background] 2パス要約: JSON解析失敗、パス1出力をそのまま使用'); + return { summary: extractedText, metadata }; + } + + console.log('[Background] 2パス要約: パス1完了、パス2(フォーマット整形)開始'); + + // パス2: フォーマット整形(低temperature) + const formatConfig: LLMConfig = { ...llmConfig, temperature: 0.3 }; + const { system: s2, user: u2 } = getFormatPrompt(documentType, parsed, earningsContext); + const formatted = await generateText(formatConfig, [ + { role: 'system', content: s2 }, + { role: 'user', content: u2 }, + ]); + + console.log('[Background] 2パス要約: パス2完了'); + return { summary: formatted, metadata }; +} + /** * Offscreen DocumentでPDFからテキストを抽出 */ diff --git a/src/lib/format-prompts.ts b/src/lib/format-prompts.ts new file mode 100644 index 0000000..6bcef15 --- /dev/null +++ b/src/lib/format-prompts.ts @@ -0,0 +1,231 @@ +/** + * 2パス要約: パス2(フォーマット整形)用プロンプト + * + * パス1で抽出したJSONデータを、固定テンプレートに沿ったテキスト形式に変換する。 + * プロンプトはシンプルに保ち、出力の安定性を最大化する。 + */ + +import type { DocumentType, EarningsContext } from './document-type'; + +const FORMAT_ROLE = `あなたはデータ整形アシスタントです。 +与えられたJSONデータを指定されたテキスト形式に正確に変換してください。`; + +const FORMAT_RULES = ` +【ルール】 +- JSONデータに含まれる情報のみを使用してください(情報の追加・捏造厳禁) +- データがnull・空文字・空配列の項目はセクションごと省略してください +- 見出しは「## 」(半角シャープ2つ + 半角スペース)で統一してください +- 指定されたセクション以外は追加しないでください +- テンプレートの順序を厳守してください`; + +// ── 決算短信テンプレート ── + +function buildEarningsTemplate(ctx: EarningsContext): string { + const isQuarterly = ctx.period !== 'fullYear'; + const forecastGroupLabel = isQuarterly ? '【通期予想】' : '【来期予想】(データがある場合のみ)'; + + return ` +--- 出力テンプレート --- + +## 決算評価(経常利益ベース) +【実績】 +- 対前年: {{evaluation.actual.vsLastYear}} +- ${isQuarterly ? '進捗' : '着地'}: {{evaluation.actual.progressOrLanding}} + +${forecastGroupLabel} +- 対前年: {{evaluation.forecast.vsLastYear}} +- ${isQuarterly ? '予想修正' : '配当'}: {{evaluation.forecast.revisionOrDividend}} + +## 全体要約 +{{summary}} + +## 業績サマリー({{performance.periodLabel}}) +{{performance.items を1行ずつ: - {name}: {amount}({change})}} + +${isQuarterly ? `## 進捗率(通期予想に対して) +- 経常利益: {{progress.ordinaryIncome}}(前年同期{{progress.lastYearProgress}}) +` : ''}## {{forecast.label}} +{{forecast.items を1行ずつ: - {name}: {amount}({change})}} + +## 修正・配当 +- 業績予想の修正: {{revision}} +- 中間配当: {{dividend.interim}} +- 期末配当: {{dividend.yearEnd}} +- 年間配当: {{dividend.annual}} +- 配当予想の修正: {{dividend.dividendRevision}} + +## トピックス +{{topics を1行ずつ: - {内容}}} + +--- テンプレートここまで ---`; +} + +// ── 業績修正テンプレート ── + +const EARNINGS_REVISION_TEMPLATE = ` +--- 出力テンプレート --- + +## 全体要約 +{{summary}} + +## 修正内容 +{{revisionItems を1行ずつ: - {name}: 前回予想{previous} → 修正後{revised}({change})}} + +## 修正理由 +{{reason}} + +## 配当予想の修正 +- 修正内容: {{dividendRevision.content}} +- 修正理由: {{dividendRevision.reason}} + +## トピックス +{{topics を1行ずつ: - {内容}}} + +--- テンプレートここまで ---`; + +// ── 配当テンプレート ── + +const DIVIDEND_TEMPLATE = ` +--- 出力テンプレート --- + +## 全体要約 +{{summary}} + +## 配当内容 +- 中間配当: {{dividendDetails.interim}} +- 期末配当: {{dividendDetails.yearEnd}} +- 年間配当: {{dividendDetails.annual}} +- 配当性向: {{dividendDetails.payoutRatio}} +- 予想修正: {{dividendDetails.revision}} +- 前期比較: {{dividendDetails.comparison}} + +## 配当方針 +{{policy}} + +## トピックス +{{topics を1行ずつ: - {内容}}} + +--- テンプレートここまで ---`; + +// ── M&Aテンプレート ── + +const MA_TEMPLATE = ` +--- 出力テンプレート --- + +## 全体要約 +{{summary}} + +## 取引概要 +- 対象会社: {{deal.targetCompany}} +- 取引内容: {{deal.transactionType}} +- スキーム: {{deal.scheme}} +- 取得比率: {{deal.acquisitionRatio}} +- 取得価額: {{deal.acquisitionPrice}} +- 契約締結日: {{deal.contractDate}} +- 取得予定日: {{deal.expectedDate}} + +## 目的 +{{purpose}} + +## 業績・連結への影響 +- 売上への影響: {{impact.revenue}} +- 利益への影響: {{impact.profit}} +- 連結範囲の変更: {{impact.consolidation}} + +## トピックス +{{topics を1行ずつ: - {内容}}} + +--- テンプレートここまで ---`; + +// ── 自己株式取得テンプレート ── + +const SHARE_REPURCHASE_TEMPLATE = ` +--- 出力テンプレート --- + +## 全体要約 +{{summary}} + +## 取得内容 +- 取得株数: {{details.shareCount}} +- 取得価額: {{details.totalAmount}} +- 取得期間: {{details.period}} +- 取得方法: {{details.method}} +- 消却予定: {{details.cancellation}} + +## 目的 +{{purpose}} + +## トピックス +{{topics を1行ずつ: - {内容}}} + +--- テンプレートここまで ---`; + +// ── その他テンプレート ── + +const OTHER_TEMPLATE = ` +--- 出力テンプレート --- + +## 全体要約 +{{summary}} + +## 開示内容 +{{content.description}} +- 対象範囲: {{content.scope}} +- 期限・予定: {{content.schedule}} + +## 業績・株価への影響 +- 影響内容: {{impact}} + +## トピックス +{{topics を1行ずつ: - {内容}}} + +--- テンプレートここまで ---`; + +/** + * パス2(フォーマット整形)用プロンプトを取得 + * + * @param documentType 文書タイプ + * @param jsonData パス1で抽出したJSONデータ + * @param earningsContext 決算コンテキスト(決算短信の場合のみ) + * @returns { system, user } — systemプロンプトとuserメッセージ + */ +export function getFormatPrompt( + documentType: DocumentType, + jsonData: unknown, + earningsContext?: EarningsContext +): { system: string; user: string } { + let template: string; + + switch (documentType) { + case 'earnings': + template = buildEarningsTemplate( + earningsContext || { period: 'q2', accountingStandard: 'jpGaap', isConsolidated: true } + ); + break; + case 'earningsRevision': + template = EARNINGS_REVISION_TEMPLATE; + break; + case 'dividend': + template = DIVIDEND_TEMPLATE; + break; + case 'ma': + template = MA_TEMPLATE; + break; + case 'shareRepurchase': + template = SHARE_REPURCHASE_TEMPLATE; + break; + case 'other': + template = OTHER_TEMPLATE; + break; + } + + const systemPrompt = `${FORMAT_ROLE}${FORMAT_RULES} +${template}`; + + const jsonStr = typeof jsonData === 'string' ? jsonData : JSON.stringify(jsonData, null, 2); + + return { + system: systemPrompt, + user: `以下のJSONデータをテンプレートに従ってテキスト形式に変換してください。\n\n${jsonStr}`, + }; +} diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.ts index 4ad62ae..0d09cad 100644 --- a/src/lib/llm-client.ts +++ b/src/lib/llm-client.ts @@ -8,6 +8,7 @@ export interface LLMConfig { apiKey: string; model: string; baseUrl?: string; // カスタムプロバイダー用 + temperature?: number; // 生成温度(0-2、低いほど安定した出力) } export interface ChatMessage { @@ -67,6 +68,7 @@ async function generateTextOpenAI(config: LLMConfig, messages: ChatMessage[]): P role: msg.role, content: msg.content, })), + ...(config.temperature !== undefined && { temperature: config.temperature }), }), }); @@ -115,6 +117,7 @@ async function generateTextAnthropic(config: LLMConfig, messages: ChatMessage[]) role: msg.role === 'assistant' ? 'assistant' : 'user', content: msg.content, })), + ...(config.temperature !== undefined && { temperature: config.temperature }), }), }); diff --git a/src/lib/prompts.ts b/src/lib/prompts.ts index a0edeb1..74d719d 100644 --- a/src/lib/prompts.ts +++ b/src/lib/prompts.ts @@ -17,6 +17,7 @@ */ import type { DocumentType, EarningsContext, EarningsPeriod } from './document-type'; +import { getJsonSchema, getEarningsRatingRulesText } from './summary-schema'; /** * プロンプト設定値 @@ -521,3 +522,103 @@ export function getPromptForDocumentType( export function getSystemPrompt(documentType: DocumentType): string { return PROMPTS[documentType]; } + +// ── 2パス要約: パス1(情報抽出)用プロンプト ── + +/** + * パス1の共通抽出ルール + */ +const EXTRACTION_ROLE = `あなたはTDnet適時開示情報の情報抽出アシスタントです。 +以下の開示文書から情報を抽出し、指定されたJSON形式で出力してください。`; + +const EXTRACTION_RULES = ` +【最優先ルール - 絶対遵守】 +1. 本文に記載されている情報のみを使用してください(捏造厳禁) +2. 数値は本文から正確に抽出してください(計算が必要な場合は本文に計算根拠がある場合のみ) +3. JSON以外は一切出力しないでください(説明文・コードブロック記法も不要) + +【重要ルール】 +4. 前年同期比/前期比の増減率が本文にある場合は必ず記載し、省略しないでください +5. 勘定科目名は本文の表記をそのまま使用してください(例: 売上収益、事業利益、経常収益など) +6. 赤字の場合は金額を「△」で始め、括弧内に「赤字」または「損失」を付記してください +7. 日付は「YYYY年M月D日」形式で統一してください +8. 金額単位は本文の表記をそのまま使用してください +9. 増減率は小数点第1位まで記載してください(例: +12.3%、△5.0%) +10. 該当情報がない項目はnullまたは空配列を設定してください`; + +const EXTRACTION_TOPICS_RULES = ` +【トピックス抽出の重点事項】 +topicsには以下の観点を最優先で拾ってください(具体的な数値を含めること): +- セグメント別・事業別の業績で全体と異なる傾向があるもの(好調/不調セグメントの売上・利益と前年比) +- 受注残高・受注増減・パイプライン・月次動向・新規出店等の先行指標 +- 一時的な要因(特別損益、為替影響、のれん償却、訴訟関連等) +- 前回開示からの変化点やサプライズ要素 +- 事業別の前年比で特異な動きがあるもの +※抽象的な記述は禁止。必ず本文中の具体的な数値・事実を含めること +※全体要約(summary)で触れていない情報のみを記載すること`; + +/** + * 決算短信用の追加抽出ルール + */ +function buildEarningsExtractionNote(ctx: EarningsContext): string { + const isQuarterly = ctx.period !== 'fullYear'; + const accountingNote = buildAccountingNote(ctx); + const ratingRules = getEarningsRatingRulesText(ctx); + + const progressNote = isQuarterly + ? ` +【進捗率について】 +- 進捗率は経常利益について「当期実績 ÷ 通期予想 × 100」で算出してください +- 通期予想が未定・ゼロ・赤字予想の場合は「算出不可(理由)」と記載してください` + : ''; + + return `${accountingNote} + +【決算評価の判定ルール】 +以下の基準に従って★評価を判定してください。 +★は★(黒星)と☆(白星)を並べて5段階で表記してください(例: ★★★★☆=4点、★★☆☆☆=2点)。 +括弧は全角()を使用してください。 +${ratingRules}${progressNote}`; +} + +/** + * パス1(情報抽出)用プロンプトを取得 + * + * @param documentType 文書タイプ + * @param extractedText 抽出されたテキスト + * @param earningsContext 決算コンテキスト(決算短信の場合のみ) + * @returns { system, user } — systemプロンプトとuserメッセージ + */ +export function getExtractionPrompt( + documentType: DocumentType, + extractedText: string, + earningsContext?: EarningsContext +): { system: string; user: string } { + const schema = getJsonSchema(documentType, earningsContext); + + const extraRules = + documentType === 'earnings' && earningsContext + ? buildEarningsExtractionNote(earningsContext) + : ''; + + const maxTopics = + documentType === 'earnings' + ? PROMPT_CONFIG.MAX_TOPICS.earnings + : PROMPT_CONFIG.MAX_TOPICS[documentType]; + + const systemPrompt = [ + EXTRACTION_ROLE, + EXTRACTION_RULES, + extraRules, + EXTRACTION_TOPICS_RULES, + `\n- topicsは最大${maxTopics}点までにしてください`, + `\n【出力JSON形式】\n${schema}`, + ] + .filter(Boolean) + .join('\n'); + + return { + system: systemPrompt, + user: `以下の開示文書から情報を抽出してください。\n\n${extractedText}`, + }; +} diff --git a/src/lib/summary-schema.ts b/src/lib/summary-schema.ts new file mode 100644 index 0000000..aa580b3 --- /dev/null +++ b/src/lib/summary-schema.ts @@ -0,0 +1,340 @@ +/** + * 文書タイプ別JSON抽出スキーマ定義 + * + * 2パス要約のパス1(情報抽出)でLLMに返させるJSONの構造を定義する。 + * TypeScript型定義と、LLMプロンプトに埋め込むスキーマ文字列の両方を提供。 + */ + +import type { DocumentType, EarningsContext } from './document-type'; + +// ── 共通型 ── + +interface FinancialItem { + name: string; + amount: string; + change?: string | null; +} + +// ── 決算短信 ── + +export interface EarningsExtraction { + summary: string; + performance: { + periodLabel: string; + items: FinancialItem[]; + }; + evaluation: { + actual: { + vsLastYear: string | null; + progressOrLanding: string | null; + }; + forecast: { + vsLastYear: string | null; + revisionOrDividend: string | null; + } | null; + } | null; + progress: { + ordinaryIncome: string; + lastYearProgress: string | null; + } | null; + forecast: { + label: string; + items: FinancialItem[]; + } | null; + revision: string | null; + dividend: { + interim: string | null; + yearEnd: string | null; + annual: string | null; + dividendRevision: string | null; + } | null; + topics: string[]; +} + +// ── 業績修正 ── + +export interface EarningsRevisionExtraction { + summary: string; + revisionItems: { + name: string; + previous: string; + revised: string; + change: string | null; + }[]; + reason: string | null; + dividendRevision: { + content: string; + reason: string | null; + } | null; + topics: string[]; +} + +// ── 配当 ── + +export interface DividendExtraction { + summary: string; + dividendDetails: { + interim: string | null; + yearEnd: string | null; + annual: string | null; + payoutRatio: string | null; + revision: string | null; + comparison: string | null; + }; + policy: string | null; + topics: string[]; +} + +// ── M&A ── + +export interface MAExtraction { + summary: string; + deal: { + targetCompany: string | null; + transactionType: string | null; + scheme: string | null; + acquisitionRatio: string | null; + acquisitionPrice: string | null; + contractDate: string | null; + expectedDate: string | null; + }; + purpose: string | null; + impact: { + revenue: string | null; + profit: string | null; + consolidation: string | null; + } | null; + topics: string[]; +} + +// ── 自己株式取得 ── + +export interface ShareRepurchaseExtraction { + summary: string; + details: { + shareCount: string | null; + totalAmount: string | null; + period: string | null; + method: string | null; + cancellation: string | null; + }; + purpose: string | null; + topics: string[]; +} + +// ── その他 ── + +export interface OtherExtraction { + summary: string; + content: { + description: string | null; + scope: string | null; + schedule: string | null; + }; + impact: string | null; + topics: string[]; +} + +// ── ユニオン型 ── + +export type ExtractionResult = + | EarningsExtraction + | EarningsRevisionExtraction + | DividendExtraction + | MAExtraction + | ShareRepurchaseExtraction + | OtherExtraction; + +// ── スキーマ文字列生成 ── + +function buildEarningsSchema(ctx: EarningsContext): string { + const isQuarterly = ctx.period !== 'fullYear'; + const progressOrLandingDesc = isQuarterly + ? 'progress(進捗率と標準進捗率を含む)' + : 'landing(対会社予想の乖離率)'; + const revisionOrDividendDesc = isQuarterly + ? 'revision(↑上方修正/→修正なし/↓下方修正 + 従来予想比)' + : 'dividend(↑増配/→据置/↓減配 + 金額変動)'; + const forecastLabel = isQuarterly ? '通期予想' : '来期予想(本文にある場合のみ)'; + const progressField = isQuarterly + ? ` + "progress": { // 進捗率(通期予想に対して) + "ordinaryIncome": "経常利益の進捗率(例: 58.3%)", + "lastYearProgress": "前年同期の進捗率(あれば)" + },` + : ` + "progress": null, // 通期決算では不要`; + + return `{ + "summary": "全体要約(2-5文。業績の傾向、通期見通し、修正/配当の有無を含む)", + "performance": { + "periodLabel": "期間ラベル(例: 第2四半期連結実績)", + "items": [ + { "name": "勘定科目名", "amount": "金額(単位付き)", "change": "前年同期比/前期比(例: +12.3%)" } + ] + }, + "evaluation": { + "actual": { + "vsLastYear": "★表記(例: ★★★★☆)+ 根拠(例: 前年同期比+15.2%)", + "progressOrLanding": "★表記 + 根拠(${progressOrLandingDesc})" + }, + "forecast": { + "vsLastYear": "★表記 + 根拠", + "revisionOrDividend": "${revisionOrDividendDesc}" + } + },${progressField} + "forecast": { + "label": "${forecastLabel}", + "items": [ + { "name": "勘定科目名", "amount": "金額", "change": "前期比(例: +8.5%)" } + ] + }, + "revision": "業績予想の修正内容(修正なしの場合は'修正なし')", + "dividend": { + "interim": "中間配当額", + "yearEnd": "期末配当額", + "annual": "年間配当額", + "dividendRevision": "配当予想の修正(旧→新、中間/期末/年間ごと)" + }, + "topics": ["具体的な数値を含むトピック(最大8点)"] +}`; +} + +function getEarningsRatingRules(ctx: EarningsContext): string { + const isQuarterly = ctx.period !== 'fullYear'; + + const standardRates: Record = { + q1: 25, + q2: 50, + q3: 75, + fullYear: 100, + }; + const standardRate = standardRates[ctx.period]; + + const progressOrLanding = isQuarterly + ? `■ 進捗: 経常利益の進捗率 − 標準進捗率(${standardRate}%)の差で判定 +★5: +10pt以上 / ★4: +5〜+10pt / ★3: ±5pt / ★2: △5〜△10pt / ★1: △10pt超 / 通期予想が未定・ゼロ・赤字→「★—」` + : `■ 着地: 経常利益の実績 vs 会社予想の乖離率で判定 +★5: +15%以上or黒字転換 / ★4: +5〜+15% / ★3: ±5% / ★2: △5〜△15% / ★1: △15%未満or赤字転落 / 会社予想なし→「—(取得不能)」`; + + const forecastRevision = isQuarterly + ? `■ 予想修正: 通期予想の従来予想からの修正方向 +↑上方修正(従来予想比+XX.X%を付記) / →修正なし / ↓下方修正(従来予想比△XX.X%を付記) / —予想未定` + : `■ 配当: 増配/減配/据置の方向 +↑増配(XX円→YY円) / →据置 / ↓減配 / —未定or記載なし`; + + return ` +■ 対前年: 経常利益の増減率で判定 +★5: +30%以上or黒字転換 / ★4: +10〜+30% / ★3: +3〜+10% / ★2: △3〜+3% / ★1: △3%未満or赤字転落 + +${progressOrLanding} + +${forecastRevision} + +※★は★(黒星)と☆(白星)を並べて5段階(例: ★★★★☆=4点)。括弧は全角() +※数値が本文にない場合は「—(取得不能)」 +※赤字で増減率が無意味な場合は「★—(赤字のため評価対象外)」`; +} + +const EARNINGS_REVISION_SCHEMA = `{ + "summary": "全体要約(1-3文。修正の方向性と主要因、配当への影響を含む)", + "revisionItems": [ + { "name": "勘定科目名", "previous": "前回予想額", "revised": "修正後額", "change": "増減率" } + ], + "reason": "修正理由(2-3行で簡潔に)", + "dividendRevision": { + "content": "配当予想の修正内容(中間/期末/年間の旧→新)", + "reason": "配当修正の理由" + }, + "topics": ["具体的な数値を含むトピック(最大4点)"] +}`; + +const DIVIDEND_SCHEMA = `{ + "summary": "全体要約(1-3文。配当水準の変化と理由を含む)", + "dividendDetails": { + "interim": "中間配当額", + "yearEnd": "期末配当額", + "annual": "年間配当額", + "payoutRatio": "配当性向", + "revision": "予想修正(旧→新、中間/期末/年間ごと)", + "comparison": "前期比較(前期年間配当→今期年間配当、増減額、増配/減配/据置)" + }, + "policy": "配当方針や株主還元方針(1-2行)", + "topics": ["具体的な数値を含むトピック(最大4点)"] +}`; + +const MA_SCHEMA = `{ + "summary": "全体要約(1-3文。取引の狙い、規模、業績影響を含む)", + "deal": { + "targetCompany": "対象会社名", + "transactionType": "取引内容(株式取得/譲渡/その他)", + "scheme": "スキーム(子会社化/持分法適用/合併/事業譲渡/その他)", + "acquisitionRatio": "取得比率", + "acquisitionPrice": "取得価額", + "contractDate": "契約締結日(YYYY年M月D日形式)", + "expectedDate": "取得予定日(YYYY年M月D日形式)" + }, + "purpose": "取引の目的(2-3行で簡潔に)", + "impact": { + "revenue": "売上への影響", + "profit": "利益への影響", + "consolidation": "連結範囲の変更" + }, + "topics": ["具体的な数値を含むトピック(最大4点)"] +}`; + +const SHARE_REPURCHASE_SCHEMA = `{ + "summary": "全体要約(1-3文。取得枠の規模、目的、消却有無を含む)", + "details": { + "shareCount": "取得株数(発行済株式総数に対する割合を含む)", + "totalAmount": "取得価額の総額", + "period": "取得期間", + "method": "取得方法(市場買付/その他)", + "cancellation": "消却予定の有無と時期" + }, + "purpose": "取得の目的(1-2行で簡潔に)", + "topics": ["具体的な数値を含むトピック(最大4点)"] +}`; + +const OTHER_SCHEMA = `{ + "summary": "全体要約(1-3文。影響の有無と重要点を含む)", + "content": { + "description": "開示の主要内容", + "scope": "対象範囲(会社/子会社/事業/その他)", + "schedule": "期限・予定(日付/期間)" + }, + "impact": "業績・株価への影響", + "topics": ["具体的な数値を含むトピック(最大4点)"] +}`; + +/** + * 文書タイプに応じたJSONスキーマ文字列を取得 + */ +export function getJsonSchema( + documentType: DocumentType, + earningsContext?: EarningsContext +): string { + switch (documentType) { + case 'earnings': + return buildEarningsSchema( + earningsContext || { period: 'q2', accountingStandard: 'jpGaap', isConsolidated: true } + ); + case 'earningsRevision': + return EARNINGS_REVISION_SCHEMA; + case 'dividend': + return DIVIDEND_SCHEMA; + case 'ma': + return MA_SCHEMA; + case 'shareRepurchase': + return SHARE_REPURCHASE_SCHEMA; + case 'other': + return OTHER_SCHEMA; + } +} + +/** + * 決算評価の判定ルール文字列を取得(決算短信のパス1プロンプト用) + */ +export function getEarningsRatingRulesText(ctx: EarningsContext): string { + return getEarningsRatingRules(ctx); +} diff --git a/src/options/Options.tsx b/src/options/Options.tsx index 1b67799..b414640 100644 --- a/src/options/Options.tsx +++ b/src/options/Options.tsx @@ -11,6 +11,7 @@ const Options: React.FC = () => { const [customUrl, setCustomUrl] = useState(''); const [useCustomModel, setUseCustomModel] = useState(false); const [extractionMode, setExtractionMode] = useState('full'); + const [twoPassMode, setTwoPassMode] = useState(true); const [saved, setSaved] = useState(false); const [autoSwitchedToCustom, setAutoSwitchedToCustom] = useState(false); const [hasAutoSwitched, setHasAutoSwitched] = useState(false); @@ -38,7 +39,7 @@ const Options: React.FC = () => { useEffect(() => { chrome.storage.sync.get( - ['provider', 'apiKey', 'model', 'customUrl', 'useCustomModel', 'extractionMode'], + ['provider', 'apiKey', 'model', 'customUrl', 'useCustomModel', 'extractionMode', 'twoPassMode'], (result) => { if (result.provider) setProvider(result.provider); if (result.apiKey) setApiKey(result.apiKey); @@ -46,6 +47,7 @@ const Options: React.FC = () => { if (result.customUrl) setCustomUrl(result.customUrl); if (result.useCustomModel !== undefined) setUseCustomModel(result.useCustomModel); if (result.extractionMode) setExtractionMode(result.extractionMode); + if (result.twoPassMode !== undefined) setTwoPassMode(result.twoPassMode); } ); loadCacheEntries(); @@ -112,6 +114,7 @@ const Options: React.FC = () => { customUrl: provider === 'custom' ? customUrl : '', useCustomModel, extractionMode, + twoPassMode, }, () => { setSaved(true); @@ -287,6 +290,42 @@ const Options: React.FC = () => { + {/* 要約モード */} +
+ + +
+ {twoPassMode ? ( +
+ 2パス要約(推奨): +
    +
  • 情報抽出→整形の2段階で安定した出力を実現
  • +
  • 性能の低いモデルでもフォーマットが安定
  • +
  • APIリクエストが2回になるためコスト・時間は約2倍
  • +
+
+ ) : ( +
+ 1パス要約: +
    +
  • 1回のリクエストで要約を生成(高速・低コスト)
  • +
  • モデルによっては出力フォーマットが不安定になる場合あり
  • +
+
+ )} +
+
+