当前位置:   article > 正文

ROS中简单实现讯飞星火大模型API调用_libsparkchain so

libsparkchain so


前言

讯飞星火认知大模型是由科大讯飞自主研发的认知智能大模型,通过学习海量的文本、代码和图像,具备跨领域的知识和语言理解能力,能基于自然对话方式理解和执行任务。目前开放了API接口供用户使用。


一、申请试用

官方链接如下:讯飞星火认知大模型
申请使用成功后,会得到自己的服务接口认证信息,包含APPID、APISecret、APIKey,在使用时需要替换为自己的。

在应用中下载Linux SDK包,官方文档说明中有SDK介绍、兼容性说明、接口调用流程、工程配置、快速集成及错误码信息。
在这里插入图片描述

二、ROS中使用

整个Spark3.5_Linux_SDK_v1.1包目录结构如下:

1.配置环境变量

cd Spark3.5_Linux_SDK_v1.1/lib/
sudo cp libSparkChain.so /usr/lib/
  • 1
  • 2

2.编写ros功能包

2.1 创建功能包

cd catkin_ws/src
catkin_create_pkg xunfei_gpt roscpp std_msgs rospy
cd ..
catkin_make
  • 1
  • 2
  • 3
  • 4

2.2 编写源文件

将Spark3.5_Linux_SDK_v1.1包中include目录下的头文件放在xunfei_gpt/include/xunfei_gpt目录下。
src中新建源文件demo.cpp,采用同步调用方式。
initSDK()函数中添加自己的服务接口认证信息

// #include "../include/sparkchain.h"
#include <iostream>
#include <string>
#include <atomic>
#include <unistd.h>
#include <regex>
#include <xunfei_gpt/sparkchain.h>
#include <ros/ros.h>
#include <std_msgs/String.h>

#define GREEN "\033[32m"
#define YELLOW "\033[33m"
#define RED "\033[31m"
#define RESET "\033[0m"

using namespace SparkChain;
using namespace std;

// async status tag
static atomic_bool finish(false);
// result cache
string final_result = "";

class SparkCallbacks : public LLMCallbacks
{
    void onLLMResult(LLMResult *result, void *usrContext)
    {
        int status = result->getStatus();
        printf(GREEN "%d:%s:%s:%s \n" RESET, status, result->getRole(), result->getContent(), usrContext);
        final_result += string(result->getContent());
        if (status == 2)
        {
            printf(GREEN "tokens:%d + %d = %d\n" RESET, result->getCompletionTokens(), result->getPromptTokens(), result->getTotalTokens());
            finish = true;
        }
    }

    void onLLMEvent(LLMEvent *event, void *usrContext)
    {
        printf(YELLOW "onLLMEventCB\n  eventID:%d eventMsg:%s\n" RESET, event->getEventID(), event->getEventMsg());
    }

    void onLLMError(LLMError *error, void *usrContext)
    {
        printf(RED "onLLMErrorCB\n errCode:%d errMsg:%s \n" RESET, error->getErrCode(), error->getErrMsg());
        finish = true;
    }
};

void uninitSDK()
{
    // 全局逆初始化
    SparkChain::unInit();
}
int initSDK()
{
    // 全局初始化
    SparkChainConfig *config = SparkChainConfig::builder();
    config->appID("your appid")        // 你的appid
        ->apiKey("your apikey")        // 你的apikey
        ->apiSecret("your apisecret"); // 你的apisecret
        // ->logLevel(0)
        // ->logPath("./aikit.log");
    int ret = SparkChain::init(config);
    printf(RED "\ninit SparkChain result:%d" RESET,ret);
    std::cout<<std::endl;
    return ret;
}
void syncLLMTest(char* input)
{
    cout << "\n######### 同步调用 #########" << endl;
    // 配置大模型参数
    LLMConfig *llmConfig = LLMConfig::builder();
    llmConfig->domain("generalv3.5");
    llmConfig->url("ws(s)://spark-api.xf-yun.com/v3.5/chat");
    Memory* window_memory = Memory::WindowMemory(5);
    LLM *syncllm = LLM::create(llmConfig,window_memory);

    // Memory* token_memory = Memory::TokenMemory(500);
    // LLM *syncllm = LLM::create(llmConfig,token_memory);

    // char* input = "你好用英语怎么说?";
        if(strcmp(input,"q") == 0){
            uninitSDK();
            // break;
        }
        // 同步请求
        LLMSyncOutput *result = syncllm->run(input);
        if (result->getErrCode() != 0)
        {
            printf(RED "\nsyncOutput: %d:%s\n\n" RESET, result->getErrCode(), result->getErrMsg());
            // continue;
        }
        else
        {
            printf(GREEN "\nsyncOutput: %s:%s\n" RESET, result->getRole(), result->getContent());
        }
        // input = "那日语呢?";
    // }
    
    // 垃圾回收
    if (syncllm != nullptr)
    {
        LLM::destroy(syncllm);
    }
}

void asyncLLMTest()
{
    cout << "\n######### 异步调用 #########" << endl;
    // 配置大模型参数
    LLMConfig *llmConfig = LLMConfig::builder();
    llmConfig->domain("generalv3.5");
    llmConfig->url("ws(s)://spark-api.xf-yun.com/v3.5/chat");

    Memory* window_memory = Memory::WindowMemory(5);
    LLM *asyncllm = LLM::create(llmConfig,window_memory);

    // Memory* token_memory = Memory::TokenMemory(500);
    // LLM *asyncllm = LLM::create(llmConfig,token_memory);

    if (asyncllm == nullptr)
    {
        printf(RED "\nLLMTest fail, please setLLMConfig before" RESET);
        return;
    }
    // 注册监听回调
    SparkCallbacks *cbs = new SparkCallbacks();
    asyncllm->registerLLMCallbacks(cbs);

    // 异步请求
    int i = 0;
    char* input = "你好用英语怎么说?";
    while (i++ < 2)
    {
        finish = false;
        char *usrContext = "myContext";
        int ret = asyncllm->arun(input, usrContext);
        if (ret != 0)
        {
            printf(RED "\narun failed: %d\n\n" RESET, ret);
            finish = true;
            continue;
        }

        int times = 0;
        while (!finish)
        { // 等待结果返回退出
            sleep(1);
            if (times++ > 10) // 等待十秒如果没有最终结果返回退出
                break;
        }
        input = "那日语呢?";
    }   
    // 垃圾回收
    
    if (asyncllm != nullptr)
    {
        LLM::destroy(asyncllm);
    }
    if (cbs != nullptr)
        delete cbs;
}
//
void VoiceCallBack(const std_msgs::String::ConstPtr & msg){
    string strListen = msg->data.c_str();
    std::cout<<"strListen:::strListen "<<strListen<<std::endl;
    char* strListenC = new char[strlen(msg->data.c_str())+ 1]; 
    strcpy(strListenC, msg->data.c_str()); // string转换成C-string
    if(strcmp(strListenC,"q")  != 0){
        syncLLMTest(strListenC);
    }
    else{
    }
}

int main(int argc, char *argv[])
{
    ros::init(argc,argv,"demo");
    ros::NodeHandle nh_;
    ros::Subscriber sub_sr = nh_.subscribe("/voiceWords", 10, VoiceCallBack);
    // ros::Publisher pub_res = nh_.advertise<>();
    cout << "\n######### llm Demo #########" << endl;
    // 全局初始化
    int ret = initSDK();
    if (ret != 0)
    {
        cout << "initSDK failed:" << ret << endl;
        return -1;
    }
    // 同步调用和异步调用选择一个执行
    // syncLLMTest(); // 同步调用
    // asyncLLMTest(); // 异步调用

    ros::Rate r(1);
    while(ros::ok()){
        ros::spinOnce();
        r.sleep();
    }
    // 退出
    uninitSDK();
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204

2.3 编写CMakeLists.txt文件

CMakeLists.txt中添加如下:

include_directories(

  ${catkin_INCLUDE_DIRS}
  include
)

add_executable(demo src/demo.cpp)
target_link_libraries(
   demo
   ${catkin_LIBRARIES} 
   libSparkChain.so -ldl -pthread
 )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2.3 运行测试

roscore
rosrun xunfei_gpt demo
  • 1
  • 2

发布询问话题:

rostopic pub /voiceWords std_msgs/String "data: '三十字以内介绍你 自己'"

rostopic pub /voiceWords std_msgs/String "data: '五十字以内介绍你能做什么'"
  • 1
  • 2
  • 3

在这里插入图片描述


总结

本文仅仅简单介绍了ROS中调用讯飞星火认知大模型API接口

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/482217
推荐阅读
相关标签
  

闽ICP备14008679号