分享:快速使用千问模型🫠 | ai | 通义千问 | 阿里百炼
XiaoYu
前言
。 example
阿里云的「百炼平台(DashScope)」提供了 OpenAI 兼容的 API,
可以通过兼容接口接入,但仍需核对模型参数、服务区域和返回结构;网络请求也要处理超时与失败。
。
模型比如:
qwen-turbo ⚡ 性价比高,适合聊天
qwen-plus 🧩 理解能力强,支持 Markdown
qwen-max:可按任务需求评估能力与成本,不仅凭名称决定是否适合企业使用。
准备
基本是Next.js 15 + TypeScript + TailwindCSS
js
yarn add @tailwindcss/typography react-markdown remark-gfm rehype-highlight highlight.js lucide-react next-themes
并在 tailwind.config.ts 中启用:
js
import type {Config} from 'tailwindcss';
import typography from '@tailwindcss/typography'; // ✅ 用 ES Module 导入
const config: Config = {
darkMode: 'class', // 支持通过 .dark 切换主题
content: [
'./app/**/*.{ts,tsx,js,jsx}',
'./pages/**/*.{ts,tsx,js,jsx}',
'./components/**/*.{ts,tsx,js,jsx}',
],
theme: {
extend: {},
},
plugins: [
typography // Here!
],
};
export default config;
配置 API Key
去阿里百炼申请一个。(挂在你的RAM账号下)

编写 API 路由(Next.js App Router)
创建文件:app/api/ai/route.ts
ts
import { NextRequest, NextResponse } from 'next/server';
import OpenAI from 'openai';
// Edge Runtime,响应更快
export const runtime = 'edge';
export async function POST(req: NextRequest) {
const data = await req.json();
try {
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY!,
baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
});
const completion = await openai.chat.completions.create({
model: 'qwen-plus',
messages: [
{ role: 'system', content: 'You are a helpful AI assistant.' },
{ role: 'user', content: data.content },
],
});
return NextResponse.json(completion);
} catch (error) {
console.error('AI 请求出错:', error);
return NextResponse.json({ error: '请求失败' }, { status: 500 });
}
}
写个聊天页面(/app/ai/page.tsx)
输入框 + 聊天列表:
tsx
'use client';
import { useState, useRef, useEffect } from 'react';
import MarkdownRenderer from '@/components/MarkdownRenderer';
import { SendHorizonal, User } from 'lucide-react';
export default function AiChatPage() {
const [messages, setMessages] = useState<{ role: string; content: string }[]>([]);
const [input, setInput] = useState('');
const [loading, setLoading] = useState(false);
const bottomRef = useRef<HTMLDivElement | null>(null);
useEffect(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), [messages]);
const handleSend = async (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim()) return;
setMessages(prev => [...prev, { role: 'user', content: input }]);
setInput('');
setLoading(true);
try {
const res = await fetch('/api/ai', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: input }),
});
const data = await res.json();
const reply = data?.choices?.[0]?.message?.content ?? '(AI 没有返回内容)';
setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
} finally {
setLoading(false);
}
};
return (
<main className="max-w-[900px] mx-auto p-4 flex flex-col">
<header className="text-lg font-semibold text-center mb-4">🤖 通义千问 AI 助手</header>
<div className="flex-1 overflow-y-auto space-y-4 border rounded-xl p-4 bg-white/70 dark:bg-zinc-900/70">
{messages.map((m, i) => (
<div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
<div
className={`px-4 py-3 rounded-2xl max-w-[80%] ${
m.role === 'user'
? 'bg-blue-600 text-white dark:bg-blue-500'
: 'bg-gray-100 dark:bg-zinc-800'
}`}
>
{m.role === 'assistant' ? (
<MarkdownRenderer content={m.content} />
) : (
<p className="whitespace-pre-wrap">{m.content}</p>
)}
</div>
</div>
))}
<div ref={bottomRef} />
</div>
<form
onSubmit={handleSend}
className="mt-3 flex items-center gap-2 border-t pt-3"
>
<input
className="flex-1 p-2 rounded-xl border dark:border-zinc-700 bg-white dark:bg-zinc-900 focus:outline-none"
placeholder="输入你的问题..."
value={input}
onChange={e => setInput(e.target.value)}
/>
<button
type="submit"
disabled={loading}
className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-xl flex items-center gap-1"
>
{loading ? '生成中...' : <><SendHorizonal size={16}/>发送</>}
</button>
</form>
</main>
);
}
Markdown 渲染组件
文件:components/MarkdownRenderer.tsx
tsx
'use client';
import { useEffect, useState, ReactNode } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';
import { Copy, Check } from 'lucide-react';
import { useTheme } from 'next-themes';
type MarkdownRendererProps = {
content: string;
className?: string;
};
// 递归提取纯文本,防止 [object Object]
function extractText(node: ReactNode): string {
if (!node) return '';
if (typeof node === 'string') return node;
if (Array.isArray(node)) return node.map(extractText).join('');
if (typeof node === 'object' && 'props' in (node as never))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return extractText((node as any).props.children);
return '';
}
export default function MarkdownRenderer({ content, className }: MarkdownRendererProps) {
const { theme } = useTheme();
const [copied, setCopied] = useState<string | null>(null);
useEffect(() => {
hljs.highlightAll();
}, [content, theme]);
const handleCopy = (code: string) => {
navigator.clipboard.writeText(code);
setCopied(code);
setTimeout(() => setCopied(null), 1200);
};
return (
<article className={`prose dark:prose-invert max-w-none ${className || ''}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight]}
components={{
code({ inline, className, children, ...props }) {
const text = extractText(children).replace(/\n$/, '');
if (inline)
return <code className="bg-zinc-800/70 px-1.5 py-0.5 rounded">{text}</code>;
const isCopied = copied === text;
return (
<div className="relative group">
<button
onClick={() => handleCopy(text)}
className="absolute top-2 right-2 p-1.5 rounded-md bg-zinc-800/60 hover:bg-zinc-700 text-gray-300 opacity-0 group-hover:opacity-100 transition-all"
>
{isCopied ? <Check size={16} /> : <Copy size={16} />}
</button>
<pre className="overflow-x-auto rounded-xl p-3">
<code className={className} {...props}>
{text}
</code>
</pre>
</div>
);
},
}}
>
{content}
</ReactMarkdown>
</article>
);
}
结果

补充说明:这是一份基础接入示例,模型名称和参数需按服务区域核对。上线时还应加入鉴权、限流和超时处理。模型返回的 Markdown/HTML 属于不可信内容,如需解析 HTML,应在解析后进行安全清理。
评论
发表评论