
Android开发:应用DeepSeek官方Api在App中实现对话功能
随着人工智能技术的不断发展,AI 在各个领域的应用越来越广泛。学习如何应用 DeepSeek API 实现对话功能,可以使开发者紧跟技术趋势,提升自己的技术竞争力。
·
文章目录
前言
随着人工智能技术的不断发展,AI 在各个领域的应用越来越广泛。学习如何应用 DeepSeek API 实现对话功能,可以使开发者紧跟技术趋势,提升自己的技术竞争力。
一、在DeepSeek官网所需的步骤
1.充值
提示:目前,DeepSeek不再提供赠送的次数,需要先进行充值才可以调用其API并实现相应功能,然而其价格便宜,只需要充值1元即可进行功能的测试。
2.创建API Key
提示:DeepSeek提供便捷的创建方式,只需要点击即可生成。
创建之后将API KEY复制并记录下来便于后续的使用
2.打开左侧栏中的接口文档快速开始
在下图中可以看到一个url地址:https://api.deepseek.com/chat/completions
左侧的语言种类选择Java
接下来可以根据左侧代码进行测试并修改。
二、对话功能的具体实现
0.新建Android项目
随着Android studio的版本更迭,要进行Java语言开发,这里要选择Empty Views Activity
1.配置权限
在AndroidManifest.xml中添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
2.导入依赖
implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3' //JSON 数据处理
implementation 'com.google.code.gson:gson:2.10.1' //JSON 序列化/反序列化
implementation 'com.squareup.okhttp3:okhttp:4.4.1' //OkHttp 是一个高效的 HTTP 客户端库,用于发送 HTTP 请求和接收响应
3.UI界面的绘制(xml文件)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!-- 使用水平 LinearLayout 包含 ImageView 和 EditText -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/edit_text_background"
android:padding="8dp">
<!-- 左侧的图片 -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/deep"
android:layout_gravity="top"
/>
<!-- 右侧的 EditText -->
<EditText
android:id="@+id/result"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="请等待AI分析解答..."
android:minHeight="200dp"
android:gravity="top"
android:inputType="textMultiLine"
android:scrollbars="vertical"
android:background="@null"
android:paddingStart="8dp"/> <!-- 文本与图片之间的间距 -->
</LinearLayout>
</ScrollView>
<View
android:layout_width="match_parent"
android:layout_height="50dp"/>
<!-- 底部输入部分 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:background="@drawable/edit_text_background"
android:hint="请输入要发送的内容"
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="200dp"
android:inputType="textMultiLine"
android:gravity="top"/>
<Button
android:id="@+id/send"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"/>
</LinearLayout>
</LinearLayout>
4.Activity方法的代码
package com.example.testdeeoseek;
import static com.google.gson.JsonParser.*;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button button;
private EditText editText1,editText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1=findViewById(R.id.content);
editText2=findViewById(R.id.result);
button=findViewById(R.id.send);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send){
Toast.makeText(MainActivity.this, "发送成功,正在思考中", Toast.LENGTH_SHORT).show();
Response response = null;
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, java.util.concurrent.TimeUnit.SECONDS) // 连接超时时间
.readTimeout(50, java.util.concurrent.TimeUnit.SECONDS) // 读取超时时间
.writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS) // 写入超时时间
.build();
Map<String, Object> params = new HashMap<>();
// 构建 messages 列表
List<Map<String, Object>> messages = new ArrayList<>();
Map<String, Object> message = new HashMap<>();
// 获取输入框的文字
String content = editText1.getText().toString();
message.put("content", content);
message.put("role", "user");
messages.add(message);
// 填充 params
params.put("messages", messages);
params.put("model", "deepseek-chat");
params.put("frequency_penalty", 0);
params.put("max_tokens", 2048);
params.put("presence_penalty", 0);
// 嵌套对象 response_format
Map<String, Object> responseFormat = new HashMap<>();
responseFormat.put("type", "text");
params.put("response_format", responseFormat);
// 其他字段
params.put("stop", null);
params.put("stream", false);
params.put("stream_options", null);
params.put("temperature", 1);
params.put("top_p", 1);
params.put("tools", null);
params.put("tool_choice", "none");
params.put("logprobs", false);
params.put("top_logprobs", null);
MediaType mediaType = MediaType.parse("application/json");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString1 = null;
try {
jsonString1 = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(params);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
RequestBody body = RequestBody.create(mediaType, jsonString1);
Request request = new Request.Builder()
.url("https://api.deepseek.com/chat/completions")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer sk-5951b2fbf64e49baa186a19425688224")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String jsonString = response.body().string();
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
JsonArray choices=jsonObject.get("choices").getAsJsonArray();
JsonObject choices0=choices.get(0).getAsJsonObject();
JsonObject message1=choices0.get("message").getAsJsonObject();
String result=message1.get("content").getAsString();
System.out.println(result);
runOnUiThread(new Runnable() {
@Override
public void run() {
editText2.setText(result);
editText1.setText("");
}
});
}
})
}
}
}
5.功能展示
更多推荐
所有评论(0)