跳到主要内容

快速上手

通过本教程,您可快速集成 AI 聊天助手功能。您可以参考 Android 客户端 demo 源码iOS 客户端 demo 源码,体验 AI 聊天助手功能和实现您自己的客户端功能。

准备工作

  1. 登录融云开发者后台。如果您还没有融云开发者账号,则注册一个

  2. 切换到您希望开通 AI 服务的应用,如果没有创建应用,请参考创建应用

  3. 在融云控制台,通过选择应用配置>AI 服务>创建智能体,创建一个智能体。

    选择您的使用场景和使用模版,并且填写智能体名称,您即可创建一个智能体。创建完成后会生成智能体 ID,智能体 ID 在后续客户端调用会使用。

  4. 调整智能体配置:

    • 调优系统提示词: 查看并根据需要修改系统提示词模板中的参数变量。
      注意

      控制台中设置的参数变量,您需要在客户端,通过 customInfo 传入的。 例如,您在系统提示词中定义了当前用户昵称是 {{myName}},对方用户的兴趣是 {{theirInterest}}。则客户端调用时,需要传入 myNametheirInterest 对应的实际值。

    • 设置交互方式:设置模型返回的超时时长。
    • 选择模型: 在智能体配置页面,您可以选择希望使用的大语言模型。
    • 设置模型参数: 如可调整采样温度,用来控制生成内容的随机性。

导入客户端 SDK

该功能还没有并入标准版 SDK。在项目的根目录 build.gradle 文件中添加融云 Maven 仓库:

gradle
allprojects {
repositories {
maven { url "https://maven.rongcloud.cn/repository/maven-releases/" }
}
}

在应用级 build.gradle 文件中添加依赖:

gradle
dependencies {
// 融云 IMKit SDK
implementation 'cn.rongcloud.sdk:im_kit:5.18.1' // 请使用AI助手版本
}

会话页面中集成AI聊天助手功能

集成步骤

1. 创建自定义会话片段

  • 创建一个新类 CustomConversationFragment 继承自 ConversationFragment
  • 关于如何创建和使用自定义会话页面,请参考会话页面文档

2. 重写 onViewCreated 方法并创建AI助手按钮

  • 调用 super.onViewCreated(view, savedInstanceState) 保留父类功能
  • 在私聊会话中创建 ImageView 作为AI助手按钮:
    Java
    if (getRongExtension().getConversationType() == Conversation.ConversationType.PRIVATE) {
    ImageView aiAssistantButton = new ImageView(getContext());
    aiAssistantButton.setImageResource(io.rong.imkit.R.drawable.rc_agent_button);
    }

3. 创建AI助手页面组件

  • 获取会话标识并创建AI助手页面:
    Java
    ConversationIdentifier conversationIdentifier = getRongExtension().getConversationIdentifier();
    AgentFacadePage agentFacadePage = new AgentFacadePage(this, conversationIdentifier);
    View agentFacadeView = agentFacadePage.onCreateView();

4. 实现模式切换逻辑

  • 为按钮添加点击事件处理,实现文本输入模式与AI助手模式的切换:
    Java
    aiAssistantButton.setOnClickListener(v -> {
    RongExtensionViewModel extensionViewModel =
    new ViewModelProvider(this).get(RongExtensionViewModel.class);

    // 根据当前状态切换模式
    if (extensionViewModel.getInputModeLiveData().getValue() == InputMode.AgentMode) {
    extensionViewModel.getInputModeLiveData().setValue(InputMode.TextInput);
    } else {
    extensionViewModel.getInputModeLiveData().setValue(InputMode.AgentMode);

    // 更新UI显示AI助手面板
    getRongExtension().getInputEditContainer()
    .setBackgroundResource(io.rong.imkit.R.drawable.rc_agent_input_bg);
    RelativeLayout container =
    getRongExtension().getContainer(RongExtension.ContainerType.BOARD);
    container.removeAllViews();
    agentFacadePage.onResume();
    container.addView(agentFacadeView);
    }
    });

5. 添加AI助手按钮到界面

  • 将按钮添加到输入框容器中完成集成:
    Java
    getRongExtension().getInputEditContainer().addView(aiAssistantButton);

示例代码

Java
/**
* 自定义会话片段,继承自 ConversationFragment
*/
public class CustomConversationFragment extends ConversationFragment {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

// 仅在单聊中添加AI助手
if (getRongExtension().getConversationType() == Conversation.ConversationType.PRIVATE) {
// 创建AI助手按钮
ImageView aiAssistantButton = new ImageView(getContext());
aiAssistantButton.setImageResource(io.rong.imkit.R.drawable.rc_agent_button);

// 获取会话标识
ConversationIdentifier conversationIdentifier = getRongExtension().getConversationIdentifier();

// 创建AI助手页面
AgentFacadePage agentFacadePage = new AgentFacadePage(this, conversationIdentifier);
View agentFacadeView = agentFacadePage.onCreateView();

// 设置AI助手按钮点击事件
aiAssistantButton.setOnClickListener(v -> {
// 切换输入模式
RongExtensionViewModel extensionViewModel =
new ViewModelProvider(this).get(RongExtensionViewModel.class);

if (extensionViewModel.getInputModeLiveData().getValue() == InputMode.AgentMode) {
// 切回文本输入模式
extensionViewModel.getInputModeLiveData().setValue(InputMode.TextInput);
} else {
// 切换到AI助手模式
extensionViewModel.getInputModeLiveData().setValue(InputMode.AgentMode);

// 更新输入框样式
getRongExtension().getInputEditContainer()
.setBackgroundResource(io.rong.imkit.R.drawable.rc_agent_input_bg);

// 显示AI助手面板
RelativeLayout container =
getRongExtension().getContainer(RongExtension.ContainerType.BOARD);
container.removeAllViews();
agentFacadePage.onResume();
container.addView(agentFacadeView);
}
});

// 将AI助手按钮添加到输入框容器
getRongExtension().getInputEditContainer().addView(aiAssistantButton);
}
}
}

自定义AI助手页面

自定义 AgentFacadePage

通过继承AgentFacadePage类创建自定义的AI助手页面:

Java
public class CustomAgentFacadePage extends AgentFacadePage {

public CustomAgentFacadePage(@NonNull Fragment fragment, ConversationIdentifier identifier) {
super(fragment, identifier);
}

@NonNull
@Override
public View onCreateView(@NonNull Context context, @NonNull LayoutInflater inflater,
@NonNull ViewGroup container, @NonNull Bundle args) {
// 调用父类方法获取基础视图
View view = super.onCreateView(context, inflater, container, args);

// 添加自定义视图或修改现有视图

return view;
}

@Override
protected void onViewReady(@NonNull AgentFacadeViewModel viewModel) {
super.onViewReady(viewModel);

// 自定义推荐项点击行为
setAgentRecommendationListener(new AgentRecommendationListener() {
@Override
public void onItemEdit(List<AgentRecommendation> recommendations) {
// 处理编辑推荐内容
if (recommendations != null && recommendations.size() == 1) {
String content = recommendations.get(0).getContent();
// 将内容填充到输入框
if (fragment instanceof ConversationFragment) {
EditText inputEditText = ((ConversationFragment) fragment)
.getRongExtension().getInputEditText();
inputEditText.setText(content);
inputEditText.setSelection(content.length());
}
}
}

@Override
public void onItemClick(List<AgentRecommendation> recommendations) {
// 处理点击推荐内容
if (recommendations != null && !recommendations.isEmpty()) {
// 实现发送消息逻辑
}
}
});
}
}

自定义 ViewModel

通过继承AgentFacadeViewModel类创建自定义的ViewModel:

Java
public class CustomAgentFacadeViewModel extends AgentFacadeViewModel {

public CustomAgentFacadeViewModel(Bundle bundle) {
super(bundle);
}

@Override
public String getAgentId() {
// 自定义AI模型选择逻辑
Context context = IMCenter.getInstance().getContext();
if (context != null) {
SharedPreferences sp = context.getSharedPreferences("ai_settings", Context.MODE_PRIVATE);
String style = sp.getString("chat_style", "default");

// 根据选择的风格返回对应的AgentId
switch (style) {
case "style1":
return "agent_id_1";
case "style2":
return "agent_id_2";
default:
return "default_agent_id";
}
}
return super.getAgentId();
}

@Override
public boolean onAgentReady(RequestRecommendationParams params, int count,
IRongCoreCallback.RecommendationRequestProgressCallback callback) {
// 自定义消息历史获取逻辑
String targetId = params.getIdentifier().getTargetId();
Conversation.ConversationType type = params.getIdentifier().getType();

// 获取最近的消息作为上下文
RongCoreClient.getInstance().getHistoryMessages(
type, targetId, null, 0, count,
RongCommonDefine.GetMessageDirection.FRONT,
new IRongCoreCallback.ResultCallback<List<Message>>() {
@Override
public void onSuccess(List<Message> messages) {
// 将消息转换为AI上下文
List<AgentContextMessage> contextMessages = convertMessagesToContext(messages);

// 回调结果
if (callback != null) {
callback.onReady(contextMessages);
}
}

@Override
public void onError(IRongCoreEnum.CoreErrorCode e) {
if (callback != null) {
callback.onReady(new ArrayList<>());
}
}
});

return true; // 返回true表示已处理
}
}

向 AI 请求推荐内容

Java
// 向智能体发起请求 RongCoreClient#requestRecommendationWithParams
public abstract void requestRecommendationWithParams(
RequestRecommendationParams params,
IRongCoreCallback.RecommendationRequestCallback callback);