feat: 初始化AI写作工坊项目

- 实现基于Vue 3 + Vite的模块化架构
- 集成DeepSeek API进行内容生成
- 支持写作范式分析功能
- 添加环境变量配置支持
- 完整的项目结构和文档
This commit is contained in:
empty
2026-01-08 10:04:59 +08:00
commit 9fb3600a6a
17 changed files with 3391 additions and 0 deletions

7
.env.example Normal file
View File

@@ -0,0 +1,7 @@
# DeepSeek API 配置
VITE_API_URL=https://api.deepseek.com/chat/completions
VITE_API_KEY=your_deepseek_api_key_here
# 其他中继平台配置示例
# VITE_API_URL=https://your-kong-gateway.com/v1/chat/completions
# VITE_API_KEY=your_bearer_token_here

35
.gitignore vendored Normal file
View File

@@ -0,0 +1,35 @@
# 依赖
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# 构建输出
dist/
build/
# 环境变量
.env
.env.local
.env.*.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# 系统文件
.DS_Store
Thumbs.db
# 日志
logs/
*.log
# 测试覆盖率
coverage/
# 临时文件
*.tmp
*.temp

150
README.md Normal file
View File

@@ -0,0 +1,150 @@
# AI 写作工坊 - 模块化版本
一个基于 Vue 3 + Vite 的专业 AI 写作辅助工具,支持结构化内容生成和写作范式分析。
## 技术栈
- **框架**: Vue 3 (Composition API)
- **构建工具**: Vite
- **状态管理**: Pinia
- **HTTP 客户端**: Axios
- **Markdown 解析**: Marked
- **样式**: Tailwind CSS
## 项目结构
```
src/
├── components/ # Vue 组件
│ ├── WriterPanel.vue # 写作面板
│ ├── AnalysisPanel.vue # 范式分析面板
│ └── MainContent.vue # 主内容区
├── stores/ # Pinia 状态管理
│ └── app.js # 应用主状态
├── api/ # API 接口
│ └── deepseek.js # DeepSeek API 封装
├── utils/ # 工具函数
│ └── promptBuilder.js # Prompt 构建器
├── App.vue # 根组件
└── main.js # 入口文件
```
## 功能特性
### 1. AI 写作工坊
- 自定义写作任务输入
- 参考案例管理
- 输出规范标签系统
- 实时流式内容生成
- Prompt 调试预览
### 2. 写作范式分析
- 预设写作范式库
- 文章智能分析
- 结构化结果展示
### 3. 配置管理
- API 地址配置
- API Key 管理
- 支持多种中继平台
## 快速开始
### 安装依赖
```bash
npm install
```
### 开发模式
```bash
npm run dev
```
### 构建生产版本
```bash
npm run build
```
### 预览生产版本
```bash
npm run preview
```
## 配置说明
### 环境变量配置
1. 复制环境变量示例文件:
```bash
cp .env.example .env
```
2. 编辑 `.env` 文件,配置您的 API 信息:
```env
# DeepSeek API 配置
VITE_API_URL=https://api.deepseek.com/chat/completions
VITE_API_KEY=your_actual_api_key_here
```
### 支持的模型
- deepseek-chat默认
- 可扩展支持其他兼容 OpenAI 格式的模型
### 安全提示
- `.env` 文件已添加到 `.gitignore`,不会被提交到版本控制
- 生产环境请使用服务器环境变量或密钥管理服务
## 开发指南
### 添加新的写作范式
`src/components/AnalysisPanel.vue` 中的 `paradigms` 数组添加新范式:
```javascript
{
type: 'new-type',
name: '新范式名称',
icon: '🎯',
description: '描述信息',
tags: ['标签1', '标签2'],
tagClass: 'bg-color-900/30 text-color-300'
}
```
### 扩展 API 支持
`src/api/` 目录下创建新的 API 类,继承基础接口:
```javascript
import BaseAPI from './base.js'
export default class NewAPI extends BaseAPI {
// 实现具体方法
}
```
### 自定义 Prompt 模板
`src/utils/promptBuilder.js` 中修改 `buildPrompt` 函数:
```javascript
export const buildPrompt = (task, constraints, references) => {
// 自定义构建逻辑
}
```
## 部署建议
### 静态部署
- Vercel
- Netlify
- GitHub Pages
### 服务器部署
- Nginx + PM2
- Docker 容器化
- CDN 加速
## 许可证
MIT License

31
index.html Normal file
View File

@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI 写作工坊 - 结构化生成工具</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* 自定义滚动条样式,适配深色主题 */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: #1e293b; }
::-webkit-scrollbar-thumb { background: #475569; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #64748b; }
/* Markdown 内容样式覆盖 */
.prose h1, .prose h2, .prose h3 { color: #e2e8f0; margin-top: 1.5em; margin-bottom: 0.8em; }
.prose p { margin-bottom: 1.2em; line-height: 1.75; color: #cbd5e1; }
.prose ul { list-style-type: disc; padding-left: 1.5em; margin-bottom: 1.2em; color: #cbd5e1; }
.prose strong { color: #60a5fa; font-weight: 600; }
.prose blockquote { border-left-color: #3b82f6; background: #1e293b; padding: 0.5rem 1rem; font-style: italic; }
.prose code { background: #334155; padding: 0.2em 0.4em; border-radius: 4px; font-size: 0.9em; color: #f8fafc; }
[v-cloak] { display: none; }
</style>
</head>
<body class="bg-slate-900 text-slate-200 h-screen overflow-hidden font-sans">
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

562
index.html.backup Normal file
View File

@@ -0,0 +1,562 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI 写作工坊 - 结构化生成工具</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
/* 自定义滚动条样式,适配深色主题 */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: #1e293b; }
::-webkit-scrollbar-thumb { background: #475569; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #64748b; }
/* Markdown 内容样式覆盖 */
.prose h1, .prose h2, .prose h3 { color: #e2e8f0; margin-top: 1.5em; margin-bottom: 0.8em; }
.prose p { margin-bottom: 1.2em; line-height: 1.75; color: #cbd5e1; }
.prose ul { list-style-type: disc; padding-left: 1.5em; margin-bottom: 1.2em; color: #cbd5e1; }
.prose strong { color: #60a5fa; font-weight: 600; }
.prose blockquote { border-left-color: #3b82f6; background: #1e293b; padding: 0.5rem 1rem; font-style: italic; }
.prose code { background: #334155; padding: 0.2em 0.4em; border-radius: 4px; font-size: 0.9em; color: #f8fafc; }
[v-cloak] { display: none; }
</style>
</head>
<body class="bg-slate-900 text-slate-200 h-screen overflow-hidden font-sans">
<div id="app" v-cloak class="flex h-full">
<aside class="w-[400px] flex flex-col border-r border-slate-700 bg-slate-800 shrink-0">
<div class="p-4 border-b border-slate-700 flex items-center justify-between">
<div class="flex items-center gap-4">
<h1 class="font-bold text-lg text-white flex items-center gap-2">
<span class="text-2xl">✍️</span>
<span v-if="currentPage === 'writer'">AI 写作工坊</span>
<span v-else>写作范式分析</span>
</h1>
<button
@click="currentPage = currentPage === 'writer' ? 'analysis' : 'writer'"
class="text-xs px-2 py-1 rounded bg-slate-700 text-slate-300 hover:bg-slate-600 transition"
>
{{ currentPage === 'writer' ? '写作范式' : '返回写作' }}
</button>
</div>
<span class="text-xs px-2 py-1 rounded bg-blue-900 text-blue-300 border border-blue-700">Pro版</span>
</div>
<div class="flex-1 overflow-y-auto p-4 space-y-6" v-if="currentPage === 'writer'">
<section>
<label class="block text-sm font-medium text-slate-400 mb-2 flex justify-between">
1. 写作任务 (User Input)
<span class="text-xs text-slate-500">{{ inputTask.length }} 字</span>
</label>
<textarea
v-model="inputTask"
class="w-full h-32 bg-slate-900 border border-slate-700 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition placeholder-slate-600 resize-none"
placeholder="请输入具体的写作要求、主题、核心观点..."
></textarea>
</section>
<section>
<div class="flex justify-between items-center mb-2">
<label class="text-sm font-medium text-slate-400">2. 参考案例 (Style Ref)</label>
<button @click="showRefInput = !showRefInput" class="text-xs text-blue-400 hover:text-blue-300">
{{ showRefInput ? '取消' : '+ 添加案例' }}
</button>
</div>
<div v-if="showRefInput" class="mb-3 p-3 bg-slate-900 rounded-lg border border-blue-500/30">
<input v-model="newRefTitle" placeholder="案例标题 (如: 乔布斯演讲)" class="w-full mb-2 bg-slate-800 border border-slate-700 rounded px-2 py-1 text-xs outline-none">
<textarea v-model="newRefContent" placeholder="粘贴优秀的参考文本..." class="w-full h-24 bg-slate-800 border border-slate-700 rounded px-2 py-1 text-xs outline-none resize-none mb-2"></textarea>
<button @click="addReference" class="w-full bg-blue-600 hover:bg-blue-500 text-xs py-1.5 rounded text-white">确认添加</button>
</div>
<div class="space-y-2">
<div v-for="(ref, index) in references" :key="index" class="group flex items-center justify-between bg-slate-700/50 p-2 rounded border border-slate-700 hover:border-slate-600">
<div class="flex items-center gap-2 overflow-hidden">
<span class="text-lg">📄</span>
<div class="flex flex-col min-w-0">
<span class="text-xs font-medium text-slate-200 truncate">{{ ref.title }}</span>
<span class="text-[10px] text-slate-500 truncate">{{ ref.content.substring(0, 20) }}...</span>
</div>
</div>
<button @click="removeReference(index)" class="text-slate-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition px-2">×</button>
</div>
<div v-if="references.length === 0" class="text-xs text-slate-600 text-center py-4 border border-dashed border-slate-700 rounded">
暂无参考案例AI 将自由发挥
</div>
</div>
</section>
<section>
<label class="block text-sm font-medium text-slate-400 mb-2">3. 输出规范 (Constraints)</label>
<div class="flex flex-wrap gap-2 mb-3">
<button
v-for="tag in presetTags"
:key="tag"
@click="toggleTag(tag)"
:class="['px-2 py-1 rounded text-xs border transition',
selectedTags.includes(tag)
? 'bg-blue-600/20 border-blue-500 text-blue-300'
: 'bg-slate-900 border-slate-700 text-slate-500 hover:border-slate-500']"
>
{{ tag }}
</button>
</div>
<input
v-model="customConstraint"
type="text"
class="w-full bg-slate-900 border border-slate-700 rounded px-3 py-2 text-xs focus:border-blue-500 outline-none"
placeholder="补充其他要求 (例如: 严禁使用'综上所述')"
>
</section>
</div>
<div class="p-4 bg-slate-800 border-t border-slate-700 space-y-3 z-10">
<div class="flex items-center justify-between">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="showPromptDebug" class="hidden">
<div class="w-8 h-4 bg-slate-900 rounded-full border border-slate-600 relative transition-colors" :class="{'bg-blue-900 border-blue-500': showPromptDebug}">
<div class="w-2 h-2 bg-slate-400 rounded-full absolute top-1 left-1 transition-transform" :class="{'translate-x-4 bg-blue-400': showPromptDebug}"></div>
</div>
<span class="text-xs text-slate-500 select-none">预览构建的 Prompt</span>
</label>
<span class="text-xs text-slate-600">deepseek</span>
</div>
<!-- API 配置 -->
<div class="space-y-2">
<input
v-model="apiUrl"
type="text"
class="w-full bg-slate-900 border border-slate-700 rounded px-3 py-2 text-xs focus:border-blue-500 outline-none"
placeholder="API 地址: https://your-kong-gateway.com/v1/chat/completions"
>
<input
v-model="apiKey"
type="password"
class="w-full bg-slate-900 border border-slate-700 rounded px-3 py-2 text-xs focus:border-blue-500 outline-none"
placeholder="API Key: Bearer YOUR_KEY"
>
</div>
<button
@click="generateContent"
:disabled="isGenerating || !inputTask"
class="w-full py-3 rounded-lg font-bold text-white shadow-lg shadow-blue-900/20 flex items-center justify-center gap-2 transition-all transform active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
:class="isGenerating ? 'bg-slate-700' : 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500'"
>
<span v-if="isGenerating" class="animate-spin text-lg">↻</span>
{{ isGenerating ? '正在思考与撰写...' : '开始生成文稿' }}
</button>
</div>
</aside>
<!-- 写作范式分析页面 -->
<aside v-if="currentPage === 'analysis'" class="w-[400px] flex flex-col border-r border-slate-700 bg-slate-800 shrink-0">
<div class="flex-1 overflow-y-auto p-4 space-y-6">
<section>
<h3 class="text-sm font-medium text-slate-400 mb-4">📚 写作范式库</h3>
<div class="space-y-3">
<div class="bg-slate-700/50 rounded-lg p-4 border border-slate-600 hover:border-blue-500 transition cursor-pointer">
<h4 class="font-medium text-white mb-2">📝 技术博客范式</h4>
<p class="text-xs text-slate-400 mb-2">适用于技术分享、教程类文章</p>
<div class="flex flex-wrap gap-1">
<span class="text-xs px-2 py-1 bg-blue-900/30 text-blue-300 rounded">问题引入</span>
<span class="text-xs px-2 py-1 bg-blue-900/30 text-blue-300 rounded">解决方案</span>
<span class="text-xs px-2 py-1 bg-blue-900/30 text-blue-300 rounded">代码示例</span>
<span class="text-xs px-2 py-1 bg-blue-900/30 text-blue-300 rounded">总结</span>
</div>
</div>
<div class="bg-slate-700/50 rounded-lg p-4 border border-slate-600 hover:border-blue-500 transition cursor-pointer">
<h4 class="font-medium text-white mb-2">📊 商业分析范式</h4>
<p class="text-xs text-slate-400 mb-2">适用于行业分析、市场报告</p>
<div class="flex flex-wrap gap-1">
<span class="text-xs px-2 py-1 bg-green-900/30 text-green-300 rounded">背景介绍</span>
<span class="text-xs px-2 py-1 bg-green-900/30 text-green-300 rounded">数据支撑</span>
<span class="text-xs px-2 py-1 bg-green-900/30 text-green-300 rounded">趋势分析</span>
<span class="text-xs px-2 py-1 bg-green-900/30 text-green-300 rounded">建议</span>
</div>
</div>
<div class="bg-slate-700/50 rounded-lg p-4 border border-slate-600 hover:border-blue-500 transition cursor-pointer">
<h4 class="font-medium text-white mb-2">🎯 产品文案范式</h4>
<p class="text-xs text-slate-400 mb-2">适用于产品介绍、营销文案</p>
<div class="flex flex-wrap gap-1">
<span class="text-xs px-2 py-1 bg-purple-900/30 text-purple-300 rounded">痛点切入</span>
<span class="text-xs px-2 py-1 bg-purple-900/30 text-purple-300 rounded">价值主张</span>
<span class="text-xs px-2 py-1 bg-purple-900/30 text-purple-300 rounded">功能亮点</span>
<span class="text-xs px-2 py-1 bg-purple-900/30 text-purple-300 rounded">行动号召</span>
</div>
</div>
<div class="bg-slate-700/50 rounded-lg p-4 border border-slate-600 hover:border-blue-500 transition cursor-pointer">
<h4 class="font-medium text-white mb-2">📖 学术论文范式</h4>
<p class="text-xs text-slate-400 mb-2">适用于学术写作、研究报告</p>
<div class="flex flex-wrap gap-1">
<span class="text-xs px-2 py-1 bg-orange-900/30 text-orange-300 rounded">摘要</span>
<span class="text-xs px-2 py-1 bg-orange-900/30 text-orange-300 rounded">引言</span>
<span class="text-xs px-2 py-1 bg-orange-900/30 text-orange-300 rounded">文献综述</span>
<span class="text-xs px-2 py-1 bg-orange-900/30 text-orange-300 rounded">方法论</span>
<span class="text-xs px-2 py-1 bg-orange-900/30 text-orange-300 rounded">结果</span>
</div>
</div>
</div>
</section>
<section>
<h3 class="text-sm font-medium text-slate-400 mb-4">🔍 范式分析工具</h3>
<textarea
v-model="analysisText"
class="w-full h-32 bg-slate-900 border border-slate-700 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition placeholder-slate-600 resize-none"
placeholder="粘贴文章内容,分析其写作范式..."
></textarea>
<button
@click="analyzeArticleParadigm"
:disabled="isAnalyzing || !analysisText"
class="mt-3 w-full bg-blue-600 hover:bg-blue-500 text-white py-2 rounded-lg text-sm font-medium transition disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ isAnalyzing ? '正在分析...' : '分析文章范式' }}
</button>
</section>
</div>
</aside>
<main class="flex-1 flex flex-col bg-slate-950 relative">
<div v-if="showPromptDebug" class="absolute inset-0 bg-slate-950/95 z-20 p-8 overflow-auto backdrop-blur-sm">
<div class="max-w-3xl mx-auto">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-bold text-yellow-500">🔧 构建的 Prompt 结构预览</h3>
<button @click="showPromptDebug = false" class="text-sm text-slate-400 hover:text-white">关闭预览</button>
</div>
<div class="bg-black/50 p-6 rounded-lg border border-slate-700 font-mono text-sm text-green-400 whitespace-pre-wrap leading-relaxed shadow-inner">
{{ constructedPrompt }}
</div>
<p class="mt-4 text-xs text-slate-500 text-center">此内容将直接发送给 API 接口</p>
</div>
</div>
<div class="h-14 border-b border-slate-800 flex items-center justify-between px-6 bg-slate-950">
<span class="text-sm font-medium text-slate-400">
{{ currentPage === 'writer' ? '输出预览' : '范式分析结果' }}
</span>
<div class="flex items-center gap-4" v-if="currentPage === 'writer'">
<span class="text-xs text-slate-600">
字数: {{ generatedContent.length }} {{ isGenerating ? '(生成中...)' : '' }}
</span>
<div class="flex gap-3">
<button @click="copyContent" class="text-xs text-slate-400 hover:text-white flex items-center gap-1 transition">
📋 复制 Markdown
</button>
<button @click="generatedContent = ''" class="text-xs text-slate-400 hover:text-red-400 flex items-center gap-1 transition">
🗑️ 清空
</button>
</div>
</div>
</div>
<div class="flex-1 overflow-y-auto p-8 md:p-12">
<div class="max-w-3xl mx-auto min-h-[500px]">
<!-- 写作页面内容 -->
<div v-if="currentPage === 'writer'">
<div v-if="!generatedContent && !isGenerating" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
<span class="text-6xl mb-4 opacity-20">⌨️</span>
<p>在左侧配置参数,点击生成开始写作</p>
</div>
<div v-else class="prose prose-invert max-w-none">
<div v-html="renderedMarkdown"></div>
<span v-if="isGenerating" class="inline-block w-2 h-5 bg-blue-500 ml-1 animate-pulse align-middle"></span>
</div>
</div>
<!-- 范式分析页面内容 -->
<div v-else class="space-y-8">
<div v-if="!analysisResult" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
<span class="text-6xl mb-4 opacity-20">📊</span>
<p>选择左侧的写作范式或使用分析工具</p>
</div>
<div v-else class="space-y-6">
<div v-if="analysisResult.error" class="bg-red-900/20 rounded-lg p-6 border border-red-700">
<h3 class="text-lg font-bold text-red-400 mb-4">分析失败</h3>
<p class="text-red-300">{{ analysisResult.message }}</p>
</div>
<div v-else class="bg-slate-900 rounded-lg p-6 border border-slate-700">
<h3 class="text-lg font-bold text-white mb-4">分析结果</h3>
<div class="prose prose-invert max-w-none">
<div v-html="marked.parse(analysisResult.analysis)"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<script>
const { createApp, computed, ref } = Vue;
createApp({
setup() {
// --- 状态数据 ---
const inputTask = ref('请帮我写一篇关于“AI 辅助编程如何改变软件开发流程”的博客文章,面向中级程序员。');
// 参考案例相关
const references = ref([
{ title: '示例:技术博客风格.txt', content: '本文深入探讨了...此处省略2000字这是为了让AI模仿这种干练的技术风格...' }
]);
const showRefInput = ref(false);
const newRefTitle = ref('');
const newRefContent = ref('');
// 规范相关
const presetTags = ['Markdown格式', '总分总结构', '数据支撑', '语气幽默', '严禁被动语态', '引用权威来源'];
const selectedTags = ref(['Markdown格式', '总分总结构']);
const customConstraint = ref('');
// 生成相关
const isGenerating = ref(false);
const generatedContent = ref('');
const showPromptDebug = ref(false);
// 页面切换
const currentPage = ref('writer'); // 'writer' 或 'analysis'
// 范式分析相关
const analysisText = ref('');
const analysisResult = ref(null);
const isAnalyzing = ref(false);
// API 配置
const apiUrl = ref('https://api.deepseek.com/chat/completions');
const apiKey = ref('YOUR_KEY');
// --- 核心逻辑Meta-Prompt 组装器 ---
const constructedPrompt = computed(() => {
let prompt = `# Role\n你是一个资深的专业写作助手请严格按照以下要求进行创作。\n\n`;
// 1. 注入规范
prompt += `# System Constraints (必须遵守)\n`;
selectedTags.value.forEach(tag => prompt += `- ${tag}\n`);
if (customConstraint.value) prompt += `- ${customConstraint.value}\n`;
prompt += `\n`;
// 2. 注入参考案例 (Few-Shot)
if (references.value.length > 0) {
prompt += `# Reference Cases (请模仿以下风格)\n`;
references.value.forEach((ref, idx) => {
prompt += `<case_${idx + 1} title="${ref.title}">\n${ref.content}\n</case_${idx + 1}>\n\n`;
});
}
// 3. 注入用户任务
prompt += `# Current Task (User Input)\n${inputTask.value}`;
return prompt;
});
const renderedMarkdown = computed(() => {
return marked.parse(generatedContent.value);
});
// --- 方法 ---
const addReference = () => {
if (!newRefTitle.value || !newRefContent.value) return;
references.value.push({
title: newRefTitle.value,
content: newRefContent.value
});
newRefTitle.value = '';
newRefContent.value = '';
showRefInput.value = false;
};
const removeReference = (index) => {
references.value.splice(index, 1);
};
const toggleTag = (tag) => {
if (selectedTags.value.includes(tag)) {
selectedTags.value = selectedTags.value.filter(t => t !== tag);
} else {
selectedTags.value.push(tag);
}
};
const generateContent = async () => {
if (!apiUrl.value || !apiKey.value || apiKey.value === 'YOUR_KEY') {
alert('请先配置 API 地址和 API Key');
return;
}
isGenerating.value = true;
generatedContent.value = '';
try {
const response = await fetch(apiUrl.value, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey.value}`
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [
{
role: 'system',
content: '你是一个资深的专业写作助手,请严格按照用户的要求进行创作。'
},
{
role: 'user',
content: constructedPrompt.value
}
],
stream: true,
temperature: 0.7
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('API Error Response:', errorText);
throw new Error(`API 请求失败: ${response.status} ${response.statusText}\n\n详细信息: ${errorText}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(line => line.trim());
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content || '';
generatedContent.value += content;
} catch (e) {
// 忽略解析错误
}
}
}
}
} catch (error) {
generatedContent.value = `## 错误\n\n${error.message}\n\n请检查 API 配置是否正确。`;
} finally {
isGenerating.value = false;
}
};
const copyContent = () => {
navigator.clipboard.writeText(generatedContent.value);
alert('已复制到剪贴板');
};
const analyzeArticleParadigm = async () => {
if (!analysisText.value.trim()) {
alert('请输入要分析的文章内容');
return;
}
isAnalyzing.value = true;
analysisResult.value = null;
try {
const response = await fetch(apiUrl.value, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey.value}`
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [
{
role: 'system',
content: '你是一个专业的写作分析师擅长分析文章的写作范式、结构和特点。请从以下几个方面分析文章1. 主要写作范式类型 2. 文章结构特点 3. 语言风格特征 4. 目标读者群体 5. 写作技巧总结。请用简洁明了的语言回答。'
},
{
role: 'user',
content: `请分析以下文章的写作范式:\n\n${analysisText.value}`
}
],
stream: false,
temperature: 0.3
})
});
if (!response.ok) {
throw new Error(`分析请求失败: ${response.status} ${response.statusText}`);
}
const data = await response.json();
analysisResult.value = {
paradigm: '技术博客范式',
features: [
'采用问题-解决方案的叙述结构',
'包含大量代码示例',
'语言简洁,逻辑清晰'
],
analysis: data.choices[0].message.content
};
} catch (error) {
analysisResult.value = {
error: true,
message: error.message
};
} finally {
isAnalyzing.value = false;
}
};
return {
inputTask,
references,
showRefInput,
newRefTitle,
newRefContent,
presetTags,
selectedTags,
customConstraint,
isGenerating,
generatedContent,
showPromptDebug,
currentPage,
analysisText,
analysisResult,
isAnalyzing,
apiUrl,
apiKey,
constructedPrompt,
renderedMarkdown,
addReference,
removeReference,
toggleTag,
generateContent,
copyContent,
analyzeArticleParadigm
};
}
}).mount('#app');
</script>
</body>
</html>

1557
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

21
package.json Normal file
View File

@@ -0,0 +1,21 @@
{
"name": "ai-writer-workshop",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.4.0",
"pinia": "^2.1.0",
"axios": "^1.6.0",
"marked": "^9.1.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.5.0",
"vite": "^5.0.0",
"dotenv": "^16.3.1"
}
}

21
src/App.vue Normal file
View File

@@ -0,0 +1,21 @@
<template>
<div class="flex h-full">
<!-- 左侧面板 -->
<WriterPanel v-if="currentPage === 'writer'" />
<AnalysisPanel v-else />
<!-- 右侧主内容区 -->
<MainContent />
</div>
</template>
<script setup>
import { computed } from 'vue'
import { useAppStore } from './stores/app'
import WriterPanel from './components/WriterPanel.vue'
import AnalysisPanel from './components/AnalysisPanel.vue'
import MainContent from './components/MainContent.vue'
const appStore = useAppStore()
const currentPage = computed(() => appStore.currentPage)
</script>

66
src/api/deepseek.js Normal file
View File

@@ -0,0 +1,66 @@
import axios from 'axios'
class DeepSeekAPI {
constructor(config) {
this.baseURL = config.url
this.apiKey = config.key
this.client = axios.create({
baseURL: this.baseURL,
timeout: 60000,
headers: {
'Content-Type': 'application/json'
}
})
}
async generateContent(prompt, options = {}) {
const response = await this.client.post('', {
model: 'deepseek-chat',
messages: [
{
role: 'system',
content: '你是一个资深的专业写作助手,请严格按照用户的要求进行创作。'
},
{
role: 'user',
content: prompt
}
],
stream: true,
temperature: 0.7,
...options
}, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
})
return response
}
async analyzeContent(text) {
const response = await this.client.post('', {
model: 'deepseek-chat',
messages: [
{
role: 'system',
content: '你是一个专业的写作分析师擅长分析文章的写作范式、结构和特点。请从以下几个方面分析文章1. 主要写作范式类型 2. 文章结构特点 3. 语言风格特征 4. 目标读者群体 5. 写作技巧总结。请用简洁明了的语言回答。'
},
{
role: 'user',
content: `请分析以下文章的写作范式:\n\n${text}`
}
],
stream: false,
temperature: 0.3
}, {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
})
return response.data
}
}
export default DeepSeekAPI

View File

@@ -0,0 +1,302 @@
<template>
<aside class="w-[400px] flex flex-col border-r border-slate-700 bg-slate-800 shrink-0">
<!-- 头部 -->
<header class="p-4 border-b border-slate-700 flex items-center justify-between">
<div class="flex items-center gap-4">
<h1 class="font-bold text-lg text-white flex items-center gap-2">
<span class="text-2xl"></span> 写作范式分析
</h1>
<button
@click="switchPage('writer')"
class="text-xs px-2 py-1 rounded bg-slate-700 text-slate-300 hover:bg-slate-600 transition"
>
返回写作
</button>
</div>
<span class="text-xs px-2 py-1 rounded bg-blue-900 text-blue-300 border border-blue-700">Pro版</span>
</header>
<!-- 内容区 -->
<div class="flex-1 overflow-y-auto p-4 space-y-6">
<!-- 写作范式库 -->
<section>
<h3 class="text-sm font-medium text-slate-400 mb-4">📚 写作范式库</h3>
<div class="space-y-3">
<div
v-for="paradigm in paradigms"
:key="paradigm.type"
@click="selectParadigm(paradigm)"
:class="['bg-slate-700/50 rounded-lg p-4 border transition cursor-pointer',
selectedParadigm?.type === paradigm.type
? 'border-blue-500 bg-blue-900/20'
: 'border-slate-600 hover:border-blue-500']"
>
<div class="flex justify-between items-start mb-2">
<h4 class="font-medium text-white">{{ paradigm.icon }} {{ paradigm.name }}</h4>
<button
v-if="selectedParadigm?.type === paradigm.type"
@click.stop="applyParadigm(paradigm)"
class="text-xs px-2 py-1 bg-blue-600 text-white rounded hover:bg-blue-500 transition"
>
应用到写作
</button>
</div>
<p class="text-xs text-slate-400 mb-2">{{ paradigm.description }}</p>
<div class="flex flex-wrap gap-1">
<span
v-for="tag in paradigm.tags"
:key="tag"
:class="['text-xs px-2 py-1 rounded', paradigm.tagClass]"
>
{{ tag }}
</span>
</div>
</div>
</div>
</section>
<!-- 范式分析工具 -->
<section>
<h3 class="text-sm font-medium text-slate-400 mb-4">🔍 范式分析工具</h3>
<textarea
v-model="analysisText"
class="w-full h-32 bg-slate-900 border border-slate-700 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition placeholder-slate-600 resize-none"
placeholder="粘贴文章内容,分析其写作范式..."
></textarea>
<div class="mt-2 flex gap-2">
<button
@click="analyzeArticle"
:disabled="isAnalyzing || !analysisText"
class="flex-1 bg-blue-600 hover:bg-blue-500 text-white py-2 rounded-lg text-sm font-medium transition disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ isAnalyzing ? '正在分析...' : '分析文章范式' }}
</button>
<button
@click="clearAnalysis"
class="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded-lg text-sm font-medium transition"
>
清空
</button>
</div>
</section>
<!-- 分析历史 -->
<section v-if="analysisHistory.length > 0">
<h3 class="text-sm font-medium text-slate-400 mb-4">📝 分析历史</h3>
<div class="space-y-2">
<div
v-for="(item, index) in analysisHistory"
:key="index"
@click="loadHistoryItem(item)"
class="bg-slate-700/30 rounded p-3 cursor-pointer hover:bg-slate-700/50 transition text-xs"
>
<div class="flex justify-between items-center">
<span class="text-slate-300">{{ item.paradigm }}</span>
<span class="text-slate-500">{{ formatDate(item.timestamp) }}</span>
</div>
<p class="text-slate-500 mt-1 truncate">{{ item.preview }}</p>
</div>
</div>
</section>
</div>
</aside>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/app'
import DeepSeekAPI from '../api/deepseek.js'
const appStore = useAppStore()
const { analysisText, isAnalyzing, selectedTags, inputTask } = storeToRefs(appStore)
// 选中的范式
const selectedParadigm = ref(null)
// 分析历史
const analysisHistory = ref([])
const paradigms = [
{
type: 'tech',
name: '技术博客范式',
icon: '📝',
description: '适用于技术分享、教程类文章',
tags: ['问题引入', '解决方案', '代码示例', '总结'],
tagClass: 'bg-blue-900/30 text-blue-300',
prompt: '请按照技术博客的范式写作包含1) 问题背景引入 2) 具体解决方案 3) 代码示例说明 4) 总结与最佳实践',
constraints: ['Markdown格式', '总分总结构', '数据支撑']
},
{
type: 'business',
name: '商业分析范式',
icon: '📊',
description: '适用于行业分析、市场报告',
tags: ['背景介绍', '数据支撑', '趋势分析', '建议'],
tagClass: 'bg-green-900/30 text-green-300',
prompt: '请按照商业分析的范式写作包含1) 行业背景介绍 2) 数据分析与支撑 3) 趋势预测 4) 战略建议',
constraints: ['Markdown格式', '数据支撑', '引用权威来源']
},
{
type: 'marketing',
name: '产品文案范式',
icon: '🎯',
description: '适用于产品介绍、营销文案',
tags: ['痛点切入', '价值主张', '功能亮点', '行动号召'],
tagClass: 'bg-purple-900/30 text-purple-300',
prompt: '请按照产品文案的范式写作包含1) 用户痛点切入 2) 核心价值主张 3) 产品功能亮点 4) 明确的行动号召',
constraints: ['语气幽默', '严禁被动语态']
},
{
type: 'academic',
name: '学术论文范式',
icon: '📖',
description: '适用于学术写作、研究报告',
tags: ['摘要', '引言', '文献综述', '方法论', '结果'],
tagClass: 'bg-orange-900/30 text-orange-300',
prompt: '请按照学术论文的范式写作包含1) 摘要 2) 引言 3) 文献综述 4) 研究方法论 5) 结果与讨论 6) 结论',
constraints: ['引用权威来源', '严禁被动语态']
}
]
// 选择范式
const selectParadigm = (paradigm) => {
selectedParadigm.value = paradigm
}
// 应用范式到写作
const applyParadigm = (paradigm) => {
// 更新写作任务
inputTask.value = paradigm.prompt
// 更新选中的约束标签
selectedTags.value = [...paradigm.constraints]
// 切换到写作页面
appStore.switchPage('writer')
// 显示提示
alert(`已应用"${paradigm.name}"到写作任务`)
}
// 分析文章
const analyzeArticle = async () => {
if (!analysisText.value.trim()) {
alert('请输入要分析的文章内容')
return
}
isAnalyzing.value = true
appStore.analysisResult = null
try {
const api = new DeepSeekAPI({
url: appStore.apiUrl,
key: appStore.apiKey
})
const result = await api.analyzeContent(analysisText.value)
// 解析分析结果,提取范式类型
const analysisContent = result.choices[0].message.content
const detectedParadigm = detectParadigm(analysisContent)
appStore.analysisResult = {
paradigm: detectedParadigm.name,
paradigmType: detectedParadigm.type,
analysis: analysisContent,
timestamp: new Date()
}
// 添加到历史记录
addToHistory(detectedParadigm.name, analysisText.value, analysisContent)
} catch (error) {
appStore.analysisResult = {
error: true,
message: error.message
}
} finally {
isAnalyzing.value = false
}
}
// 检测文章范式
const detectParadigm = (analysis) => {
const text = analysis.toLowerCase()
if (text.includes('技术') || text.includes('代码') || text.includes('问题')) {
return paradigms[0] // 技术博客
} else if (text.includes('商业') || text.includes('市场') || text.includes('数据')) {
return paradigms[1] // 商业分析
} else if (text.includes('产品') || text.includes('营销') || text.includes('用户')) {
return paradigms[2] // 产品文案
} else if (text.includes('学术') || text.includes('研究') || text.includes('文献')) {
return paradigms[3] // 学术论文
}
return paradigms[0] // 默认技术博客
}
// 添加到历史记录
const addToHistory = (paradigm, text, analysis) => {
const historyItem = {
paradigm,
text,
analysis,
preview: text.substring(0, 50) + '...',
timestamp: new Date()
}
// 限制历史记录数量
analysisHistory.value.unshift(historyItem)
if (analysisHistory.value.length > 10) {
analysisHistory.value = analysisHistory.value.slice(0, 10)
}
// 保存到本地存储
localStorage.setItem('analysisHistory', JSON.stringify(analysisHistory.value))
}
// 加载历史记录项
const loadHistoryItem = (item) => {
analysisText.value = item.text
appStore.analysisResult = {
paradigm: item.paradigm,
analysis: item.analysis,
timestamp: item.timestamp
}
}
// 清空分析
const clearAnalysis = () => {
analysisText.value = ''
appStore.analysisResult = null
selectedParadigm.value = null
}
// 格式化日期
const formatDate = (date) => {
const now = new Date()
const diff = now - new Date(date)
const minutes = Math.floor(diff / 60000)
const hours = Math.floor(diff / 3600000)
const days = Math.floor(diff / 86400000)
if (minutes < 1) return '刚刚'
if (minutes < 60) return `${minutes}分钟前`
if (hours < 24) return `${hours}小时前`
if (days < 7) return `${days}天前`
return new Date(date).toLocaleDateString()
}
// 组件挂载时加载历史记录
onMounted(() => {
const saved = localStorage.getItem('analysisHistory')
if (saved) {
analysisHistory.value = JSON.parse(saved)
}
})
</script>

View File

@@ -0,0 +1,239 @@
<template>
<main class="flex-1 flex flex-col bg-slate-950 relative">
<!-- Prompt调试面板 -->
<div v-if="showPromptDebug && currentPage === 'writer'" class="absolute inset-0 bg-slate-950/95 z-20 p-8 overflow-auto backdrop-blur-sm">
<div class="max-w-3xl mx-auto">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-bold text-yellow-500">🔧 构建的 Prompt 结构预览</h3>
<button @click="showPromptDebug = false" class="text-sm text-slate-400 hover:text-white">关闭预览</button>
</div>
<div class="bg-black/50 p-6 rounded-lg border border-slate-700 font-mono text-sm text-green-400 whitespace-pre-wrap leading-relaxed shadow-inner">
{{ constructedPrompt }}
</div>
<p class="mt-4 text-xs text-slate-500 text-center">此内容将直接发送给 API 接口</p>
</div>
</div>
<!-- 顶部工具栏 -->
<header class="h-14 border-b border-slate-800 flex items-center justify-between px-6 bg-slate-950">
<span class="text-sm font-medium text-slate-400">
{{ currentPage === 'writer' ? '输出预览' : '范式分析结果' }}
</span>
<div class="flex items-center gap-4" v-if="currentPage === 'writer'">
<span class="text-xs text-slate-600">
字数: {{ generatedContent.length }} {{ isGenerating ? '(生成中...)' : '' }}
</span>
<div class="flex gap-3">
<button @click="copyContent" class="text-xs text-slate-400 hover:text-white flex items-center gap-1 transition">
📋 复制 Markdown
</button>
<button @click="clearContent" class="text-xs text-slate-400 hover:text-red-400 flex items-center gap-1 transition">
🗑 清空
</button>
</div>
</div>
</header>
<!-- 主内容区 -->
<div class="flex-1 overflow-y-auto p-8 md:p-12">
<div class="max-w-3xl mx-auto min-h-[500px]">
<!-- 写作页面内容 -->
<div v-if="currentPage === 'writer'">
<div v-if="!generatedContent && !isGenerating" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
<span class="text-6xl mb-4 opacity-20"></span>
<p>在左侧配置参数点击生成开始写作</p>
</div>
<div v-else class="prose prose-invert max-w-none">
<div v-html="renderedMarkdown"></div>
<span v-if="isGenerating" class="inline-block w-2 h-5 bg-blue-500 ml-1 animate-pulse align-middle"></span>
</div>
</div>
<!-- 范式分析页面内容 -->
<div v-else class="space-y-8">
<div v-if="!analysisResult" class="h-full flex flex-col items-center justify-center text-slate-700 mt-20">
<span class="text-6xl mb-4 opacity-20">📊</span>
<p>选择左侧的写作范式或使用分析工具</p>
</div>
<div v-else class="space-y-6">
<div v-if="analysisResult.error" class="bg-red-900/20 rounded-lg p-6 border border-red-700">
<h3 class="text-lg font-bold text-red-400 mb-4">分析失败</h3>
<p class="text-red-300">{{ analysisResult.message }}</p>
</div>
<div v-else class="space-y-6">
<!-- 分析结果头部 -->
<div class="bg-slate-900 rounded-lg p-6 border border-slate-700">
<div class="flex items-center justify-between mb-4">
<h3 class="text-lg font-bold text-white">分析结果</h3>
<span class="text-xs px-3 py-1 rounded-full bg-blue-900/30 text-blue-300 border border-blue-700">
{{ analysisResult.paradigm }}
</span>
</div>
<!-- 分析内容 -->
<div class="prose prose-invert max-w-none">
<div v-html="marked.parse(analysisResult.analysis)"></div>
</div>
<!-- 操作按钮 -->
<div class="mt-6 flex gap-3">
<button
@click="copyAnalysis"
class="text-xs px-4 py-2 bg-slate-700 hover:bg-slate-600 text-white rounded transition"
>
📋 复制分析结果
</button>
<button
@click="applyToWriting"
class="text-xs px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded transition"
>
应用到写作
</button>
</div>
</div>
<!-- 范式详情卡片 -->
<div v-if="getParadigmDetails()" class="bg-slate-900/50 rounded-lg p-6 border border-slate-700">
<h4 class="text-md font-bold text-white mb-4">{{ getParadigmDetails().name }}特点</h4>
<div class="grid grid-cols-2 gap-4">
<div>
<h5 class="text-xs font-medium text-slate-400 mb-2">结构要素</h5>
<div class="flex flex-wrap gap-1">
<span
v-for="tag in getParadigmDetails().tags"
:key="tag"
:class="['text-xs px-2 py-1 rounded', getParadigmDetails().tagClass]"
>
{{ tag }}
</span>
</div>
</div>
<div>
<h5 class="text-xs font-medium text-slate-400 mb-2">适用场景</h5>
<p class="text-xs text-slate-300">{{ getParadigmDetails().description }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</template>
<script setup>
import { computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/app'
import { buildPrompt } from '../utils/promptBuilder.js'
import { marked } from 'marked'
const appStore = useAppStore()
const {
currentPage,
showPromptDebug,
generatedContent,
isGenerating,
analysisResult,
inputTask,
selectedTags,
customConstraint,
references
} = storeToRefs(appStore)
// 范式定义
const paradigms = [
{
type: 'tech',
name: '技术博客范式',
description: '适用于技术分享、教程类文章',
tags: ['问题引入', '解决方案', '代码示例', '总结'],
tagClass: 'bg-blue-900/30 text-blue-300',
prompt: '请按照技术博客的范式写作包含1) 问题背景引入 2) 具体解决方案 3) 代码示例说明 4) 总结与最佳实践',
constraints: ['Markdown格式', '总分总结构', '数据支撑']
},
{
type: 'business',
name: '商业分析范式',
description: '适用于行业分析、市场报告',
tags: ['背景介绍', '数据支撑', '趋势分析', '建议'],
tagClass: 'bg-green-900/30 text-green-300',
prompt: '请按照商业分析的范式写作包含1) 行业背景介绍 2) 数据分析与支撑 3) 趋势预测 4) 战略建议',
constraints: ['Markdown格式', '数据支撑', '引用权威来源']
},
{
type: 'marketing',
name: '产品文案范式',
description: '适用于产品介绍、营销文案',
tags: ['痛点切入', '价值主张', '功能亮点', '行动号召'],
tagClass: 'bg-purple-900/30 text-purple-300',
prompt: '请按照产品文案的范式写作包含1) 用户痛点切入 2) 核心价值主张 3) 产品功能亮点 4) 明确的行动号召',
constraints: ['语气幽默', '严禁被动语态']
},
{
type: 'academic',
name: '学术论文范式',
description: '适用于学术写作、研究报告',
tags: ['摘要', '引言', '文献综述', '方法论', '结果'],
tagClass: 'bg-orange-900/30 text-orange-300',
prompt: '请按照学术论文的范式写作包含1) 摘要 2) 引言 3) 文献综述 4) 研究方法论 5) 结果与讨论 6) 结论',
constraints: ['引用权威来源', '严禁被动语态']
}
]
// 计算构建的Prompt
const constructedPrompt = computed(() => {
return buildPrompt(
inputTask.value,
[...selectedTags.value, customConstraint.value].filter(Boolean),
references.value
)
})
// 渲染Markdown
const renderedMarkdown = computed(() => {
return marked.parse(generatedContent.value)
})
// 复制内容
const copyContent = () => {
navigator.clipboard.writeText(generatedContent.value)
alert('已复制到剪贴板')
}
// 清空内容
const clearContent = () => {
generatedContent.value = ''
}
// 复制分析结果
const copyAnalysis = () => {
if (analysisResult.value) {
navigator.clipboard.writeText(analysisResult.value.analysis)
alert('分析结果已复制到剪贴板')
}
}
// 应用到写作
const applyToWriting = () => {
if (analysisResult.value) {
const paradigm = getParadigmDetails()
if (paradigm) {
inputTask.value = paradigm.prompt
selectedTags.value = [...paradigm.constraints]
appStore.switchPage('writer')
alert(`已应用"${paradigm.name}"到写作任务`)
}
}
}
// 获取范式详情
const getParadigmDetails = () => {
if (!analysisResult.value?.paradigmType) return null
return paradigms.find(p => p.type === analysisResult.value.paradigmType)
}
</script>

View File

@@ -0,0 +1,230 @@
<template>
<aside class="w-[400px] flex flex-col border-r border-slate-700 bg-slate-800 shrink-0">
<!-- 头部 -->
<header class="p-4 border-b border-slate-700 flex items-center justify-between">
<div class="flex items-center gap-4">
<h1 class="font-bold text-lg text-white flex items-center gap-2">
<span class="text-2xl"></span> AI 写作工坊
</h1>
</div>
<span class="text-xs px-2 py-1 rounded bg-blue-900 text-blue-300 border border-blue-700">Pro版</span>
</header>
<!-- 内容区 -->
<div class="flex-1 overflow-y-auto p-4 space-y-6">
<!-- 写作任务 -->
<section>
<label class="block text-sm font-medium text-slate-400 mb-2 flex justify-between">
1. 写作任务 (User Input)
<span class="text-xs text-slate-500">{{ inputTask.length }} </span>
</label>
<textarea
v-model="inputTask"
class="w-full h-32 bg-slate-900 border border-slate-700 rounded-lg p-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition placeholder-slate-600 resize-none"
placeholder="请输入具体的写作要求、主题、核心观点..."
></textarea>
</section>
<!-- 参考案例 -->
<section>
<div class="flex justify-between items-center mb-2">
<label class="text-sm font-medium text-slate-400">2. 参考案例 (Style Ref)</label>
<button @click="showRefInput = !showRefInput" class="text-xs text-blue-400 hover:text-blue-300">
{{ showRefInput ? '取消' : '+ 添加案例' }}
</button>
</div>
<div v-if="showRefInput" class="mb-3 p-3 bg-slate-900 rounded-lg border border-blue-500/30">
<input v-model="newRefTitle" placeholder="案例标题" class="w-full mb-2 bg-slate-800 border border-slate-700 rounded px-2 py-1 text-xs outline-none">
<textarea v-model="newRefContent" placeholder="粘贴优秀的参考文本..." class="w-full h-24 bg-slate-800 border border-slate-700 rounded px-2 py-1 text-xs outline-none resize-none mb-2"></textarea>
<button @click="addReference" class="w-full bg-blue-600 hover:bg-blue-500 text-xs py-1.5 rounded text-white">确认添加</button>
</div>
<div class="space-y-2">
<div v-for="(ref, index) in references" :key="index" class="group flex items-center justify-between bg-slate-700/50 p-2 rounded border border-slate-700 hover:border-slate-600">
<div class="flex items-center gap-2 overflow-hidden">
<span class="text-lg">📄</span>
<div class="flex flex-col min-w-0">
<span class="text-xs font-medium text-slate-200 truncate">{{ ref.title }}</span>
<span class="text-[10px] text-slate-500 truncate">{{ ref.content.substring(0, 20) }}...</span>
</div>
</div>
<button @click="removeReference(index)" class="text-slate-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition px-2">×</button>
</div>
</div>
</section>
<!-- 输出规范 -->
<section>
<label class="block text-sm font-medium text-slate-400 mb-2">3. 输出规范 (Constraints)</label>
<div class="flex flex-wrap gap-2 mb-3">
<button
v-for="tag in presetTags"
:key="tag"
@click="toggleTag(tag)"
:class="['px-2 py-1 rounded text-xs border transition',
selectedTags.includes(tag)
? 'bg-blue-600/20 border-blue-500 text-blue-300'
: 'bg-slate-900 border-slate-700 text-slate-500 hover:border-slate-500']"
>
{{ tag }}
</button>
</div>
<input
v-model="customConstraint"
type="text"
class="w-full bg-slate-900 border border-slate-700 rounded px-3 py-2 text-xs focus:border-blue-500 outline-none"
placeholder="补充其他要求"
>
</section>
</div>
<!-- 底部操作区 -->
<footer class="p-4 bg-slate-800 border-t border-slate-700 space-y-3">
<div class="flex items-center justify-between">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" v-model="showPromptDebug" class="hidden">
<div class="w-8 h-4 bg-slate-900 rounded-full border border-slate-600 relative transition-colors" :class="{'bg-blue-900 border-blue-500': showPromptDebug}">
<div class="w-2 h-2 bg-slate-400 rounded-full absolute top-1 left-1 transition-transform" :class="{'translate-x-4 bg-blue-400': showPromptDebug}"></div>
</div>
<span class="text-xs text-slate-500 select-none">预览构建的 Prompt</span>
</label>
<span class="text-xs text-slate-600">deepseek</span>
</div>
<!-- API配置 -->
<div class="space-y-2">
<input
v-model="apiUrl"
type="text"
class="w-full bg-slate-900 border border-slate-700 rounded px-3 py-2 text-xs focus:border-blue-500 outline-none"
placeholder="API 地址"
>
<input
v-model="apiKey"
type="password"
class="w-full bg-slate-900 border border-slate-700 rounded px-3 py-2 text-xs focus:border-blue-500 outline-none"
placeholder="API Key"
>
</div>
<button
@click="generateContent"
:disabled="isGenerating || !inputTask"
class="w-full py-3 rounded-lg font-bold text-white shadow-lg shadow-blue-900/20 flex items-center justify-center gap-2 transition-all transform active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
:class="isGenerating ? 'bg-slate-700' : 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500'"
>
<span v-if="isGenerating" class="animate-spin text-lg"></span>
{{ isGenerating ? '正在思考与撰写...' : '开始生成文稿' }}
</button>
</footer>
</aside>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/app'
import { buildPrompt } from '../utils/promptBuilder.js'
import DeepSeekAPI from '../api/deepseek.js'
import { marked } from 'marked'
const appStore = useAppStore()
const {
inputTask,
references,
showRefInput,
newRefTitle,
newRefContent,
selectedTags,
customConstraint,
isGenerating,
generatedContent,
showPromptDebug,
apiUrl,
apiKey
} = storeToRefs(appStore)
const presetTags = ['Markdown格式', '总分总结构', '数据支撑', '语气幽默', '严禁被动语态', '引用权威来源']
// 添加参考案例
const addReference = () => {
if (!newRefTitle.value || !newRefContent.value) return
references.value.push({
title: newRefTitle.value,
content: newRefContent.value
})
newRefTitle.value = ''
newRefContent.value = ''
showRefInput.value = false
}
// 删除参考案例
const removeReference = (index) => {
references.value.splice(index, 1)
}
// 切换标签
const toggleTag = (tag) => {
if (selectedTags.value.includes(tag)) {
selectedTags.value = selectedTags.value.filter(t => t !== tag)
} else {
selectedTags.value.push(tag)
}
}
// 生成内容
const generateContent = async () => {
if (!apiUrl.value || !apiKey.value || apiKey.value === 'YOUR_KEY') {
alert('请先配置 API 地址和 API Key')
return
}
isGenerating.value = true
generatedContent.value = ''
try {
const api = new DeepSeekAPI({ url: apiUrl.value, key: apiKey.value })
const prompt = buildPrompt(inputTask.value, [...selectedTags.value, customConstraint.value].filter(Boolean), references.value)
const response = await api.generateContent(prompt)
const reader = response.body.getReader()
const decoder = new TextDecoder()
while (true) {
const { done, value } = await reader.read()
if (done) break
const chunk = decoder.decode(value)
const content = parseStreamResponse(chunk)
generatedContent.value += content
}
} catch (error) {
generatedContent.value = `## 错误\n\n${error.message}\n\n请检查 API 配置是否正确。`
} finally {
isGenerating.value = false
}
}
// 解析流式响应
const parseStreamResponse = (chunk) => {
const lines = chunk.split('\n').filter(line => line.trim())
const contents = []
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6)
if (data === '[DONE]') continue
try {
const parsed = JSON.parse(data)
const content = parsed.choices?.[0]?.delta?.content || ''
if (content) contents.push(content)
} catch (e) {
// 忽略解析错误
}
}
}
return contents.join('')
}
</script>

9
src/main.js Normal file
View File

@@ -0,0 +1,9 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')

63
src/stores/app.js Normal file
View File

@@ -0,0 +1,63 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { config } from '../utils/config.js'
export const useAppStore = defineStore('app', () => {
// 页面状态
const currentPage = ref('writer') // 'writer' 或 'analysis'
// API配置 - 从环境变量读取
const apiUrl = ref(config.apiUrl)
const apiKey = ref(config.apiKey)
// 写作相关
const inputTask = ref('请帮我写一篇关于"AI 辅助编程如何改变软件开发流程"的博客文章,面向中级程序员。')
const references = ref([
{ title: '示例:技术博客风格.txt', content: '本文深入探讨了...此处省略2000字这是为了让AI模仿这种干练的技术风格...' }
])
const selectedTags = ref(['Markdown格式', '总分总结构'])
const customConstraint = ref('')
// 生成相关
const isGenerating = ref(false)
const generatedContent = ref('')
// 分析相关
const analysisText = ref('')
const analysisResult = ref(null)
const isAnalyzing = ref(false)
// UI状态
const showPromptDebug = ref(false)
const showRefInput = ref(false)
const newRefTitle = ref('')
const newRefContent = ref('')
// 切换页面
const switchPage = (page) => {
currentPage.value = page
}
return {
// 状态
currentPage,
apiUrl,
apiKey,
inputTask,
references,
selectedTags,
customConstraint,
isGenerating,
generatedContent,
analysisText,
analysisResult,
isAnalyzing,
showPromptDebug,
showRefInput,
newRefTitle,
newRefContent,
// 方法
switchPage
}
})

36
src/utils/config.js Normal file
View File

@@ -0,0 +1,36 @@
// 环境变量配置
export const config = {
// API 配置
apiUrl: import.meta.env.VITE_API_URL || 'https://api.deepseek.com/chat/completions',
apiKey: import.meta.env.VITE_API_KEY || 'YOUR_KEY',
// 应用配置
appVersion: '1.0.0',
isDev: import.meta.env.DEV,
mode: import.meta.env.MODE
}
// 验证必需的环境变量
export const validateConfig = () => {
const errors = []
if (!config.apiUrl) {
errors.push('API URL 未配置')
}
if (!config.apiKey || config.apiKey === 'YOUR_KEY') {
errors.push('API Key 未配置或使用默认值')
}
return errors
}
// 获取配置摘要(用于调试)
export const getConfigSummary = () => {
return {
apiUrl: config.apiUrl,
hasApiKey: config.apiKey !== 'YOUR_KEY',
mode: config.mode,
isDev: config.isDev
}
}

View File

@@ -0,0 +1,43 @@
export const buildPrompt = (task, constraints, references) => {
let prompt = `# Role\n你是一个资深的专业写作助手,请严格按照以下要求进行创作。\n\n`
// 1. 注入规范
prompt += `# System Constraints (必须遵守)\n`
constraints.forEach(tag => prompt += `- ${tag}\n`)
prompt += `\n`
// 2. 注入参考案例 (Few-Shot)
if (references.length > 0) {
prompt += `# Reference Cases (请模仿以下风格)\n`
references.forEach((ref, idx) => {
prompt += `<case_${idx + 1} title="${ref.title}">\n${ref.content}\n</case_${idx + 1}>\n\n`
})
}
// 3. 注入用户任务
prompt += `# Current Task (User Input)\n${task}`
return prompt
}
export const parseStreamResponse = (chunk) => {
const lines = chunk.split('\n').filter(line => line.trim())
const contents = []
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6)
if (data === '[DONE]') continue
try {
const parsed = JSON.parse(data)
const content = parsed.choices?.[0]?.delta?.content || ''
if (content) contents.push(content)
} catch (e) {
// 忽略解析错误
}
}
}
return contents.join('')
}

19
vite.config.js Normal file
View File

@@ -0,0 +1,19 @@
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig(({ mode }) => {
// 加载环境变量
const env = loadEnv(mode, process.cwd(), '')
return {
plugins: [vue()],
server: {
port: 3000,
open: true
},
define: {
// 将环境变量暴露给客户端
__APP_ENV__: JSON.stringify(env)
}
}
})