使用 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 请求和响应处理,确保系统高效运行。

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

相关推荐
小蠢驴打代码21 小时前
我做了一个工具:一键同步 Claude Code、Cursor、Codex 的 MCP 和 Skills 配置
openai·claude·cursor
时光之源2 天前
Visual Studio | Marketplace创建发布者(Create Publisher)时无法创建的问题解决方案
ide·vscode·visual studio·plugin·cursor
小北的博客2 天前
如何在 Android studio 中使用 cursor 插件
android studio·intellij-idea·ai编程·android-studio·插件·cursor
小星AI3 天前
Claude Code Agent SDK 从入门到精通,一步到位
人工智能·agent·cursor
鸿_H3 天前
杂记11---ubuntu2204环境vscode/cursor切换中文输入法
vscode·cursor·ubuntu2204
daixin88483 天前
cursor无法正常使用gpt5.5等模型解决方案
java·redis·cursor
Mac的实验室3 天前
要裂开了!ChatGPT要手机号验证了?注册Codex要求验证电话号码怎么办?2026年登陆Codex要手机号验证的解决办法
openai·ai编程·cursor
Cyning5 天前
2026-04-28 :让 AI 接手代码库不再开盲盒
ai编程·cursor
DanCheOo5 天前
我开源了一个工具,把 Cursor 37 个对话提取成 519 条结构化记忆——再也不用给 AI 重复解释背景了
aigc·ai编程·cursor
Cyning5 天前
2026-04-27 : Tech Graph — 自动渲染 + 跨仓契约 + CI 门禁
ai编程·cursor