使用 Cursor + NestJS 接入星火 Spark Lite 免费模型

前言

星火 Spark Lite 是讯飞的一个免费开放的轻量级大语言模型,适合低算力推理与模型精调等场景。

以下是使用 Cursor + NestJS 接入星火 Spark Lite 的教程,使用的是openai这个第三方库进行接入到后端,给前端提供接口使用。

准备工作

  1. 注册账号并获取 API 密钥
    • 访问讯飞星火官网,注册账号并完成实名认证。
    • 在控制台创建应用,获取 AppIDAPI KeySecret Key
    • 领取免费的 Spark Lite API 密钥。
  2. 环境配置
    • 安装 Node.js 和 npm。
    • 创建 NestJS 项目并进入项目目录。

踩坑点

最开始询问时没有添加指定要openai这个库,cursor默认将其api接入,感觉有点不优雅,就使用openai这个库,后续添加过多也可以统一。

为了减少弯路,先去官网查看官方文档,将其喂给cursor,让其将python改为nodejs的nest框架

改完之后发现运行不起来,报错了,根据猜测应该是之前api的返回格式和openai返回的格式不一样

知道原因之后,让cursor进行修改

最终的代码

  1. 安装必要的依赖

    bash 复制代码
    npm install openai
    npm install -D @types/node
  2. 创建 StarfireService

    typescript 复制代码
    // starfire.service.ts
    import { Injectable, InternalServerErrorException } from '@nestjs/common';
    import axios from 'axios';
    
    @Injectable()
    export class StarfireService {
      private readonly apiKey = 'your_api_key'; // 替换为你的 API Key
        
    	constructor() {
            this.openai = new OpenAI({
                apiKey: this.apiKey,
                baseURL: 'https://spark-api-open.xf-yun.com/v1'//这里必须要改为baseUrl,要不然就不生效
            })
        }
      async getResponse(prompt: string) {
        try {
          const response = await this.openai.chat.completions.create({
                    model: 'lite',//这个是免费的模型,切记不要写spark-lite
                    messages: [
                        { role: 'system', content: prompt },
                        { role: 'user', content: createSparkDto.userInput },
                    ],
                    stream: true,
                });
          return response.data;
        } catch (error) {
          console.error('Error communicating with Starfire API:', error);
          throw new InternalServerErrorException('Unable to fetch response from Starfire API');
        }
      }
    }

创建控制器

typescript 复制代码
// starfire.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { StarfireService } from './starfire.service';

@Controller('starfire')
export class StarfireController {
  constructor(private readonly starfireService: StarfireService) {}

  @Post('chat')
  async chat(@Body('prompt') prompt: string) {
    return this.starfireService.getResponse(prompt);
  }
}

注册模块

typescript 复制代码
// app.module.ts
import { Module } from '@nestjs/common';
import { StarfireService } from './starfire.service';
import { StarfireController } from './starfire.controller';

@Module({
  controllers: [StarfireController],
  providers: [StarfireService],
})
export class AppModule {}

测试 API

使用前端控制台发送 POST 请求到 http://localhost:3000/starfire/chat,请求体不用包括 prompt 字段,在后端已经使用了自定义的提示词。

最终的效果,后端控制台输出,速度还是杠杠滴,快去试试吧

完整代码示例

以下是完整的代码结构及关键文件内容:

文件结构

lua 复制代码
├── src
│   ├── starfire
│   │   ├── starfire.controller.ts
│   │   ├── starfire.service.ts
│   │   └── dto
│   │       └── create-chat.dto.ts
│   └── app.module.ts
└── package.json

DTO 文件

typescript 复制代码
// dto/create-chat.dto.ts
export class CreateChatDto {
  prompt: string;
}

七、注意事项

  1. API 密钥:不要泄露你的 API 密钥,确保它安全地存储在配置文件或环境变量中。
  2. 错误处理:在实际应用中,增强错误处理逻辑以提升用户体验。
  3. 性能优化:根据需要优化 API 请求和响应处理,确保系统高效运行。

此教程提供了一个基础的接入方式,你可以根据实际需求进行扩展和优化。如果你在接入过程中遇到问题,可以参考讯飞星火的官方文档或寻求社区支持。

相关推荐
时光之源1 天前
Labelme安装及使用说明教程
vscode·数据集·cursor·labelme·数据标注
Sestid2 天前
前端AI编程使用技巧(后续会更新cursor和claude code for vscode)
前端·vscode·ai编程·claude·cursor
倔强的石头_3 天前
突破 Cursor 模型限制:低成本接入 GLM-5 与第三方大模型实践指南
cursor
AmyLin_20015 天前
MiniMax Skills 技能体系分析
cursor·codex·minimax·claude code·skills·minimax skills
装不满的克莱因瓶6 天前
Cursor中agent、plan、ask三种模式区别于对比
人工智能·ai·大模型·ai编程·cursor
程序员爱德华11 天前
AI Coding 使用教程
copilot·cursor·trae·claude code·ai coding
Irene199112 天前
拥抱 AI 原生 IDE,Cursor 我来了
cursor
Filwaod12 天前
Cursor+IDEA开发问题
java·idea·cursor
shughui14 天前
Cursor下载安装以及和VSCode的区别(附安装包)
ide·vscode·ai·编辑器·cursor