DEV Community

rio lo
rio lo

Posted on

HarmonyOS application integration DeepSeek API complete development tutorial

preface

In the field of AI application development, DeepSeek, as an advanced large language model, provides powerful natural language processing capabilities. This article will detail how to integrate the DeepSeek API in the HarmonyOS to implement AI conversational capabilities. Whether you are a HarmonyOS app developer or an AI technology enthusiast, you can quickly master the integration method with this tutorial.

Environment preparation

Development tools

DevEco Studio 3.1 or later (official IDE for HarmonyOS App Development)

HarmonyOS SDK API 9 or later

Account preparation

Visit the official DeepSeek platform (https://api.deepseek.com)

Sign up for a developer account and create an app

Get the API key in the console (sk-xxx format)

Description of the project structure

First, create a tool folder in the HarmonyOS project, and the example structure in this document is as follows:

plaintext

src/main/ets/

├── utils/

│ └── AIRequest_Util.ts # ai request util

├── pages/

│ └── testHttp.ets # testPage

└── entry/

└── main_pages.json   # page router
Enter fullscreen mode Exit fullscreen mode

Full code implementation

  1. AI request util(AIRequest_Util.ts)

typescript

import http from '@ohos.net.http';

import hilog from '@ohos.hilog';

/**

  • DeepSeek AI API请求工具类

  • 封装HTTP请求逻辑与响应处理

*/

export class AIRequest_Util {

/**

*/

request(question: string, callback: (text: string) => void) {

hilog.info(0x0000, 'testTag', 'ALiYunHttpUtils request invoke. question: %{public}s', question);






let httpRequest = http.createHttp();





const requestData = {

  model: "deepseek-chat", 

  messages: [

    { role: "system", content: "你是人工智能AI" },

    { role: "user", content: question } 

  ],

  "stream": false 

};






httpRequest.request(

  "https://api.deepseek.com/chat/completions", // DeepSeek API

  {

    method: http.RequestMethod.POST, 

    header: {

      "Content-Type": "application/json", 

      "Authorization": "Bearer sk-3e4695d9f07c454c8cb9d59822d27987" // APIkey

    },

    extraData: JSON.stringify(requestData), 

    readTimeout: 60000, 

    connectTimeout: 60000, 

    usingProtocol: http.HttpProtocol.HTTP1_1

  }, (err, data: http.HttpResponse) => {



    if (err) {

      hilog.error(0x0000, 'testTag', '请求失败: %{public}s', JSON.stringify(err));

      httpRequest.destroy();

      callback("请求失败,请检查网络");

      return;

    }




    try {

      // 5. 解析响应数据

      const response = JSON.parse(data.result as string);

      hilog.info(0x0000, 'testTag', '完整响应: %{public}s', JSON.stringify(response));




      // 检查API错误

      if (response.error) {

        hilog.error(0x0000, 'testTag', 'API错误: %{public}s', response.error.message);

        callback(`API错误: ${response.error.message}`);

        return;

      }




      // 提取AI回答内容

      if (response.choices && response.choices.length > 0) {

        const content = response.choices[0].message.content;

        if (content) {

          hilog.info(0x0000, 'testTag', '提取到的文本: %{public}s', content);

          callback(content);

          return;

        }

      }




      throw new Error("未找到有效响应内容");

    } catch (e) {

      hilog.error(0x0000, 'testTag', '解析失败: %{public}s', e.message);

      callback("解析响应失败");

    } finally {

      // 释放资源

      httpRequest.destroy();

    }

  }

)
Enter fullscreen mode Exit fullscreen mode

}

}

// 导出单例对象

export const DeepSeek = new AIRequest_Util();

  1. page(testHttp.ets)

typescript

import { DeepSeek } from '../utils/AIRequest_Util'; // 导入工具类

@Entry

@Component

struct testHttp {

@State answer: string = '' // 存储AI回答

build() {

Column() {

  // 交互按钮

  Button('click')

    .width('50%')

    .onClick(() => {

      // 调用DeepSeek API

      DeepSeek.request("你是谁", (answer) => {

        // 更新UI显示回答

        this.answer = answer

      })

    })



  // 显示回答内容

  Text(this.answer)

    .fontSize(30)

    .margin({ top: 20 })

}

.height('100%')

.width('100%')

.justifyContent(FlexAlign.Center)

.alignItems(HorizontalAlign.Center)
Enter fullscreen mode Exit fullscreen mode

}

}

  1. page router(main_pages.json)

json

{

"src": [

{

  "pages": [

    "pages/testHttp"

  ],

  "name": "entry",

  "window": {

    "designWidth": 720,

    "autoDesignWidth": true

  }

}
Enter fullscreen mode Exit fullscreen mode

]

Analysis of functional modules

  1. The core process of API requests

The DeepSeek API call follows these steps:

Create an instance of the HTTP request

Build an OpenAI-compliant request body (DeepSeek-compatible OpenAI interface specification)

Set the request header (including the API key and content type)

Send a POST request to the DeepSeek API endpoint

Process response data and extract AI responses

  1. Request parameters

Parameter Name, Type, and description

model string is the name of the model, and deepseek-chat is the dialogue model

Messages array, which contains system prompts and user questions

messages.role string is the message role, system is the system prompt, user is the user input, and assistant is the AI answer

messages.content string The content of the message

Whether stream boolean enables streaming response, false is off (used in this example)

  1. Error Handling Mechanism

Three layers of error handling are implemented in the code:

Network request errors (e.g., timeouts, connection failures)

API interface errors (e.g., authentication failures, parameter errors)

Response parsing errors (e.g., data format is abnormal)

Results:

Image description

Problems you may encounter:

05-31 23:37:56.504 40524-28380 A00000/testTag E API error: Insufficient Balance

If the balance of the API key is insufficient, go to the official website to charge money

Top comments (0)