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

前言

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

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

准备工作

  1. 注册账号并获取 API 密钥 :
    • 访问讯飞星火官网,注册账号并完成实名认证。
    • 在控制台创建应用,获取 AppID、API Key 和 Secret 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 请求和响应处理,确保系统高效运行。

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

相关推荐
一缕82年的清风12 小时前
从Cursor杀向命令行:当AI接管终端,为什么资深架构师反而很少开IDE了?
claude·cursor·gemini
网络毒刘1 天前
把个人 Prompt 库迁到 AtomGit:版本化、评审与在 Cursor 中通过 @ 引用
prompt·cursor·atomgit·版本化·工具实践
网络毒刘1 天前
Rules 冲突排查:多条规则互相打架时如何用优先级、范围与示例消歧
agent·ai编程·cursor·rules
网络毒刘1 天前
端到端:用 Cursor Agent 完成「小功能 + 单测 + PR 描述」并附人工验收清单
单元测试·agent·ai编程·cursor·工具实践
一缕82年的清风1 天前
别只拿 Claude 当聊天窗口!Projects 专属大脑与 Artifacts 高阶玩法实测
claude·cursor
用户539418729072 天前
.cursorrules 写了等于没写?我把“让 Cursor 读懂你项目”的规则和上下文整理成一套模板
ai编程·cursor
网络毒刘2 天前
Cursor 排障剧本:卡住、乱改、漏测三类故障的复现提问与上下文裁剪法
agent·cursor·上下文·排障·工具实践
网络毒刘2 天前
开源 Aider 工作流实战:Git 提交驱动的 AI 结对,与 Cursor 何时互补
git·ai编程·cursor·aider
Maynor9963 天前
让 AI 编程助手学会做视频、做 PPT:Agent Skills 入门与安装全指南
人工智能·aigc·ai编程·效率工具·cursor·claude code
网络毒刘4 天前
Token 用量观测实战:从会话结构拆前缀/工具/生成,建立个人降本仪表盘
人工智能·性能优化·token·cursor