从零开始:用TypeScript和Cohere构建智能助手应用

云信安装大师
90
AI 质量分
10 5 月, 2025
2 分钟阅读
0 阅读

从零开始:用TypeScript和Cohere构建智能助手应用

引言

在AI技术快速发展的今天,构建自己的智能助手不再是一件遥不可及的事情。本文将带你从零开始,使用TypeScript和Cohere的API创建一个简单的智能助手应用。无论你是前端开发者还是AI爱好者,都能通过本教程快速上手。

准备工作

在开始之前,请确保你已经准备好以下内容:

  1. Node.js环境:建议安装最新LTS版本(18.x或更高)
  2. TypeScript:我们将使用TypeScript来获得更好的类型安全
  3. Cohere账号:注册Cohere并获取API密钥
  4. 代码编辑器:如VS Code

环境设置

首先创建项目并安装必要依赖:

代码片段
# 创建项目目录
mkdir cohere-assistant && cd cohere-assistant

# 初始化npm项目
npm init -y

# 安装TypeScript和相关依赖
npm install typescript ts-node @types/node --save-dev

# 安装Cohere SDK和其他必要包
npm install cohere-ai dotenv express @types/express

项目结构

我们的项目将采用以下结构:

代码片段
cohere-assistant/
├── src/
│   ├── index.ts         # 主应用入口
│   ├── cohere.ts        # Cohere服务封装
│   └── types.ts         # 类型定义
├── .env                 # 环境变量文件
├── tsconfig.json        # TypeScript配置
└── package.json

第一步:配置Cohere客户端

1. 创建.env文件

首先在项目根目录创建.env文件,添加你的Cohere API密钥:

代码片段
COHERE_API_KEY=your_api_key_here
PORT=3000

注意:不要将此文件提交到版本控制中!确保将它添加到你的.gitignore中。

2. 创建Cohere服务封装

src/cohere.ts中创建一个封装Cohere API的服务类:

代码片段
import { CohereClient } from 'cohere-ai';
import dotenv from 'dotenv';

dotenv.config();

// 初始化Cohere客户端
const cohere = new CohereClient({
    token: process.env.COHERE_API_KEY || '',
});

/**
 * 向Cohere发送消息并获取响应
 * @param message 用户输入的消息
 * @returns Promise<string> Cohere生成的响应
 */
export async function getAIResponse(message: string): Promise<string> {
    try {
        const response = await cohere.generate({
            model: 'command',
            prompt: message,
            maxTokens: 300,
            temperature: 0.7,
        });

        return response.generations[0].text;
    } catch (error) {
        console.error('Error calling Cohere API:', error);
        return 'Sorry, I encountered an error processing your request.';
    }
}

代码解释
1. dotenv.config()加载我们的环境变量
2. CohereClient是官方提供的SDK客户端
3. getAIResponse函数封装了生成文本的核心逻辑:
model: 我们使用’command’模型,这是Cohere的一个强大通用模型
maxTokens: 限制响应长度(约300个单词)
temperature: 控制创造性的参数(0-1之间)

第二步:创建Express服务器

src/index.ts中设置一个简单的Express服务器:

代码片段
import express from 'express';
import { getAIResponse } from './cohere';

const app = express();
const port = process.env.PORT || 3000;

// Middleware配置
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// API路由 - POST /api/chat
app.post('/api/chat', async (req, res) => {
    const { message } = req.body;

    if (!message) {
        return res.status(400).json({ error: 'Message is required' });
    }

    try {
        const aiResponse = await getAIResponse(message);
        res.json({ response: aiResponse });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

// 启动服务器
app.listen(port, () => {
    console.log(`Server running on http://localhost:${port}`);
});

第三步:测试你的智能助手

1. 启动服务器

代码片段
npx ts-node src/index.ts

你应该看到输出:”Server running on http://localhost:3000″

2. 使用curl测试API

打开另一个终端窗口,运行:

代码片段
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"message":"请用简单的方式解释量子计算"}'

你应该会收到一个关于量子计算的简明解释。

3. Postman测试(可选)

如果你更喜欢图形界面:
1. URL: POST http://localhost:3000/api/chat
2. Body (raw JSON):

代码片段
{
    "message": "写一首关于编程的俳句"
}

进阶功能:添加对话历史

为了让对话更有连贯性,我们可以改进我们的服务来维护对话上下文。修改src/coherer.ts:

“`typescript
// …之前的导入保持不变…

interface Conversation {
userMessage: string;
aiResponse: string;
}

let conversationHistory: Conversation[] = [];

/**
* 生成包含上下文的prompt字符串
*/
function buildPromptWithContext(newMessage: string): string {
let prompt = ”;

代码片段
// 添加历史对话到prompt中(最多保留5轮)
conversationHistory.slice(-5).forEach((conv) => {
    prompt += `用户:${conv.userMessage}\n`;
    prompt += `助手:${conv.aiResponse}\n\n`;
});

// 添加新消息并明确指示这是新的问题/指令 
prompt += `用户:${newMessage}\n助手:`;

return prompt;

}

export async function getAIResponse(message: string): Promise {
try {
const fullPrompt = buildPromptWithContext(message);

代码片段
    const response = await coherer.generate({
        model: 'command',
        prompt: fullPrompt,
        maxTokens: —400,
        temperature: —0.—5,
        stopSequences— —— ['\n用户— —'] —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— ———— ———— ———— ———— ———— ———— ———— ———— ———— ———— ———— ———— ———— ———— —
原创 高质量