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

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

相关推荐
寅时码17 小时前
消除大模型幻觉,让AI-IDE真正理解代码,打通LSP与AI的任督二脉
visual studio code·cursor·mcp
hsfxuebao2 天前
Cursor快速上手+科学使用指南
cursor
大熊猫侯佩4 天前
无需自己写半行代码:让 AI 编程智能体(Agent)化身神笔马良为我们自动仿制 App 界面
swiftui·agent·cursor
全宝4 天前
⚡我做了一个批量下载 VSCode 插件的小工具
前端·visual studio code·cursor
qiyue774 天前
如何选择AI IDE?对比Cursor分析功能差异
ai编程·cursor·trae
老纪的技术唠嗑局4 天前
Vibe Coding 时代的开源社区开发新体验
cursor·mcp·vibecoding
极客密码5 天前
Cursor再见,隔壁Augment赠送的免费一个月650额度会员我用上了!
aigc·ai编程·cursor
mCell5 天前
受够Cursor卡成蜗牛!我换用Argument,每月白嫖300次真香!
ai编程·visual studio code·cursor
龙萱坤诺5 天前
【教程】无需迁移IDE!Augment原生插件实现Cursor无缝平替 Claude-4无限用
cursor·cursor工具·augment code
人生都在赌6 天前
一个AI工作流如何让代码审查从手动到智能?实战拆解
ai编程·devops·cursor