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

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

相关推荐
Aaaaaaaaaaayou15 小时前
体验一下 Midscene.js,基于 AI 的 UI 自动化
cursor·mcp
tommyrunner1 天前
换个角度认识 MCP
ai编程·cursor·mcp
Baihai IDP2 天前
深度解析 Cursor(逐行解析系统提示词、分享高效制定 Cursor Rules 的技巧...)
人工智能·ai编程·cursor·genai·智能体·llms
飞哥数智坊3 天前
不用Rules=白用Cursor!一套规则文件,让团队代码生成合规率飙升80%
人工智能·cursor
不识君3 天前
我用IDEA搭配Trae提升编写java代码的开发效率
cursor·trae
前端日常开发3 天前
让cursor用CSS 动画实现电子书翻页效果
cursor
子昕3 天前
突发!Cursor推出Ultra版:200刀一个月,Pro用户开始慌了
cursor
轻语呢喃3 天前
用AI编程助手打造小游戏:从《谁是卧底》看Trae和Cursor的实战应用
cursor·trae
AryaNimbus3 天前
“我 Cursor Pro 怎么用三天就没了?”——500 次额度的真相是这样
前端·cursor
Baihai_IDP4 天前
深度解析 Cursor(逐行解析系统提示词、分享高效制定 Cursor Rules 的技巧...)
人工智能·ai编程·cursor