Иностранный язык с ИИ: Deepseek Languages Models
Создадим полный Android JAVA проект приложения, выполняющего запрос к ИИ chat.deepseek.com для генерирования учебного упражнения для изучения иностранных языков по методике Oflameron WORDS
Полный код Android приложения для отправки запроса в DeepSeek AI API:
Deepseek API Example
build.gradle (Module: app)
gradle
plugins {
id 'com.android.application'
}
android {
namespace 'com.example.deepseekgerman'
compileSdk 34
defaultConfig {
applicationId "com.example.deepseekgerman"
minSdk 21
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
// Для HTTP запросов
implementation 'com.squareup.okhttp3:okhttp:4.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'
// Для JSON обработки
implementation 'com.google.code.gson:gson:2.10.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
Deepseek API Example
AndroidManifest.xml
xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deepseekgerman">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="DeepSeek German Learning"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Deepseek API Example
activity_main.xml
xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:background="#f5f5f5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DeepSeek German Learning Exercise"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#333333"
android:gravity="center"
android:layout_marginBottom="16dp"
android:padding="12dp"
android:background="#ffffff"
android:elevation="2dp" />
<Button
android:id="@+id/generateButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Сгенерировать упражнение"
android:textSize="16sp"
android:layout_marginBottom="16dp"
android:backgroundTint="#2196F3"
android:textColor="#ffffff"
android:padding="12dp" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="16dp"
android:visibility="gone" />
<TextView
android:id="@+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textColor="#333333"
android:background="#ffffff"
android:padding="16dp"
android:elevation="1dp"
android:lineSpacingExtra="4dp"
android:text="Нажмите кнопку для генерации упражнения..." />
</LinearLayout>
</ScrollView>
Deepseek API Example
MainActivity.java
java
package com.example.deepseekgerman;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.IOException;
import okhttp3.*;
public class MainActivity extends AppCompatActivity {
private TextView resultTextView;
private Button generateButton;
private ProgressBar progressBar;
private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
private static final String API_KEY = "YOUR_DEEPSEEK_API_KEY"; // Замените на ваш API ключ
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
setupClient();
setupButtonListener();
}
private void initializeViews() {
resultTextView = findViewById(R.id.resultTextView);
generateButton = findViewById(R.id.generateButton);
progressBar = findViewById(R.id.progressBar);
}
private void setupClient() {
client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
}
private void setupButtonListener() {
generateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new GenerateExerciseTask().execute();
}
});
}
private class GenerateExerciseTask extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
generateButton.setEnabled(false);
resultTextView.setText("Генерация упражнения...");
}
@Override
protected String doInBackground(Void... voids) {
return generateExerciseWithDeepSeek();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
generateButton.setEnabled(true);
if (result != null && !result.isEmpty()) {
resultTextView.setText(result);
} else {
resultTextView.setText("Ошибка при генерации упражнения. Проверьте API ключ и подключение к интернету.");
}
}
}
private String generateExerciseWithDeepSeek() {
try {
// Создаем JSON запрос для DeepSeek API
JSONObject requestBody = new JSONObject();
requestBody.put("model", "deepseek-chat");
requestBody.put("temperature", 0.7);
requestBody.put("max_tokens", 2000);
JSONArray messages = new JSONArray();
JSONObject systemMessage = new JSONObject();
systemMessage.put("role", "system");
systemMessage.put("content", "You are a helpful assistant that creates German language learning exercises using the Oflameron WORDS method.");
messages.put(systemMessage);
JSONObject userMessage = new JSONObject();
userMessage.put("role", "user");
String prompt = createPrompt();
userMessage.put("content", prompt);
messages.put(userMessage);
requestBody.put("messages", messages);
RequestBody body = RequestBody.create(
requestBody.toString(),
MediaType.parse("application/json; charset=utf-8")
);
Request request = new Request.Builder()
.url(DEEPSEEK_API_URL)
.post(body)
.addHeader("Authorization", "Bearer " + API_KEY)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
String responseBody = response.body().string();
return parseDeepSeekResponse(responseBody);
} else {
return "Ошибка API: " + response.code() + " - " + response.message();
}
} catch (Exception e) {
e.printStackTrace();
return "Исключение: " + e.getMessage();
}
}
private String createPrompt() {
return "Let's prepare a learning exercise using the Oflameron WORDS method for learning German. " +
"To do this, select 15 German words on the topic \"I study at the university. I attend lectures and seminars, live on campus, go to the gym and the student cafeteria.\" " +
"Then, create special words from them by processing each one using the following algorithm:\n" +
"Transform the words into one-dimensional matrices (rows), the matrix elements being the letters from the original words (i.e., you need to separate the word into letters). This will be the original matrix.\n" +
"Randomly re-sort the elements of each matrix (use only one sorting option for each word). The number and composition of letters should not change. This will be the target matrix. \n" +
"Create a special word (special word) from the target matrix as follows: by strictly, letter by letter, sequentially combining all the matrix elements into a single continuous row without any changes in order, omissions, or interpretations. Remember the original German words and their corresponding special words for future use.\n" +
"Display only the final result on the screen: on each line, the original German word, the number of letters in the original word, the original matrix, the target matrix, the resulting corresponding special word, and count and write the number of letters in the special word.\n" +
"Compose a 5-6-sentence text on the topic chosen above using the original 15 German words, but replace them in the finished text with the corresponding special words that you prepared.\n" +
"Write the finished text and, for verification, show in parentheses at the end of each sentence the original German words used, replaced with the special words.\n\n" +
"Please provide the complete exercise in Russian language response.";
}
private String parseDeepSeekResponse(String responseBody) {
try {
JSONObject jsonResponse = new JSONObject(responseBody);
JSONArray choices = jsonResponse.getJSONArray("choices");
if (choices.length() > 0) {
JSONObject firstChoice = choices.getJSONObject(0);
JSONObject message = firstChoice.getJSONObject("message");
return message.getString("content");
} else {
return "No response generated";
}
} catch (Exception e) {
e.printStackTrace();
return "Error parsing response: " + e.getMessage();
}
}
}
Deepseek API Example
Альтернативная версия с использованием Gson (дополнительно)
build.gradle (добавить зависимость)
gradle
implementation 'com.google.code.gson:gson:2.10.1'
DeepSeekResponse.java (вспомогательный класс)
java
package com.example.deepseekgerman;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class DeepSeekResponse {
@SerializedName("choices")
private List<Choice> choices;
public List<Choice> getChoices() {
return choices;
}
public static class Choice {
@SerializedName("message")
private Message message;
public Message getMessage() {
return message;
}
}
public static class Message {
@SerializedName("content")
private String content;
public String getContent() {
return content;
}
}
}
Deepseek API Example
Обновленный метод parseDeepSeekResponse с Gson:
java
private String parseDeepSeekResponse(String responseBody) {
try {
Gson gson = new Gson();
DeepSeekResponse response = gson.fromJson(responseBody, DeepSeekResponse.class);
if (response.getChoices() != null && !response.getChoices().isEmpty()) {
return response.getChoices().get(0).getMessage().getContent();
} else {
return "No response generated";
}
} catch (Exception e) {
e.printStackTrace();
return "Error parsing response: " + e.getMessage();
}
}
Deepseek API Example
Инструкция по настройке:
1. 'Замените API ключ': В строке `private static final String API_KEY = "YOUR_DEEPSEEK_API_KEY";` укажите ваш действительный API ключ от DeepSeek.
2. 'Проверьте URL API': Убедитесь, что URL `https://api.deepseek.com/v1/chat/completions` корректен для DeepSeek API.
3. 'Разрешения': Приложение запрашивает разрешения на доступ в интернет.
4. 'Обработка ошибок': Приложение обрабатывает основные ошибки сети и API.
Особенности приложения:
- 'Асинхронная обработка': Запросы к API выполняются в фоновом потоке
- 'Индикатор загрузки': Показывает прогресс генерации
- 'Обработка ошибок': Сообщает об ошибках сети или API
- 'Форматированный вывод': Отображает сгенерированное упражнение в читаемом формате
- 'Прокручиваемый интерфейс': Для удобного просмотра длинного текста
Deepseek API Example
При нажатии на кнопку приложение отправит запрос в DeepSeek AI и отобразит сгенерированное учебное упражнение по немецкому языку.
Deepseek API Example
...