快速上手
通过本教程,您可快速集成 AI 聊天助手功能。您可以参考 Android 客户端 demo 源码和 iOS 客户端 demo 源码,体验 AI 聊天助手功能和实现您自己的客户端功能。
准备工作
-
切换到您希望开通 AI 服务的应用,如果没有创建应用,请参考创建应用。
提示目前仅北京数据中心可创建智能体。
-
在融云控制台,通过选择应用配置>AI 服务>创建智能体,创建一个智能体。
选择您的使用场景和使用模版,并且填写智能体名称,您即可创建一个智能体。创建完成后会生成智能体 ID,智能体 ID 在后续客户端调用会使用。
-
调整智能体配置:
- 调优系统提示词: 查看并根据需要修改系统提示词模板中的参数变量。
注意
控制台中设置的参数变量,您需要在客户端,通过
customInfo
传入的。 例如,您在系统提示词中定义了当前用户昵称是{{myName}}
,对方用户的兴趣是{{theirInterest}}
。则客户端调用时,需要传入myName
和theirInterest
对应的 实际值。 - 设置交互方式:设置模型返回的超时时长。
- 选择模型: 在智能体配置页面,您可以选择希望使用的大语言模型。
- 设置模型参数: 如可调整采样温度,用来控制生成内容的随机性。
- 调优系统提示词: 查看并根据需要修改系统提示词模板中的参数变量。
导入客户端 SDK
- Android
- iOS
该功能还没有并入标准版 SDK,使用 pod
集成时需要引入特定的 source
地址:https://github.com/rongcloud/ios-rongcloudspec.git
,
podfile
内容如下:
source 'https://github.com/rongcloud/ios-rongcloudspec.git'
target 'AppProject' do
#pod sdk
pod 'RongCloudIM','5.18.1'
...
end
该功能还没有并入标准版 SDK。在项目的根目录 build.gradle 文件中添加融云 Maven 仓库:
allprojects {
repositories {
maven { url "https://maven.rongcloud.cn/repository/maven-releases/" }
}
}
在应用级 build.gradle 文件中添加依赖:
dependencies {
// 融云 IMKit SDK
implementation 'cn.rongcloud.sdk:im_kit:5.18.1' // 请使用AI助手版本
}
会话页面中集成AI聊天助手功能
- Android
- iOS
集成步骤
1. 创建自定义 AI 会话页面
- 创建继承自
RCConversationViewController
的自定义会话页面 - 实现必要的代理协议:
RCAgentMessageDataSource
、RCAgentFacadeUIDelegate
、RCAgentViewDelegate
@interface RCAIConversationViewController : RCConversationViewController<RCAgentMessageDataSource,RCAgentFacadeUIDelegate,RCAgentViewDelegate>
@property (nonatomic, strong) RCAgentFacadeModel *agent;
@end
2. 配置 AI 助手功能
- 配置 Agent 代理信息和 AI 按钮
- 实现 AI 按钮点击事件处理
- 设置输入框中的 Agent 按钮布局
/// AI 按钮点击事件
- (void)buttonAgentClicked {
if (self.agent.agentView.superview) {
[self.agent.agentView removeFromSuperview];
[self.chatSessionInputBarControl resetToDefaultStatus];
} else {
[self.chatSessionInputBarControl setDefaultInputType:RCChatSessionInputBarInputExtention];
[self.chatSessionInputBarControl containerViewWillAppear];
UIView *pluginBoardView = self.chatSessionInputBarControl.pluginBoardView;
self.agent.agentView.frame = pluginBoardView.bounds;
if (![RCDAgentContext isAbilityValidForKey:RCDAgentEnableKey]) {
[self.agent.agentView showStatusView:self.unavailableView];
} else {
if (!self.recommendationEnable) {
[self.agent requestRecommendationWith:self.agentTag.agentID
customInfo:[self customPrompt]];
}
}
[pluginBoardView addSubview:self.agent.agentView];
}
}
- (void)configureForAgent {
RCUserInfo *user = [[RCIM sharedRCIM] getUserInfoCache:self.targetId];
self.targetUsername = user.name;
user = [[RCIM sharedRCIM] currentUserInfo];
self.currentUsername = user.name;
RCConversationIdentifier *identifier = [RCConversationIdentifier new];
identifier.targetId = self.targetId;
identifier.channelId = self.channelId;
identifier.type = self.conversationType;
self.identifier = identifier;
self.agent.dataSource = self;
self.agent.uiDelegate = self;
self.agent.agentView.backgroundView.image = [UIImage imageNamed:@"ai_agent_bg"];
self.agent.agentView.delegate = self;
[self configureAgentButton];
[self reconfigurePlusButton];
}
3. 配置输入框和视图管理
- 配置输入框中的 Agent 按钮位置
- 实现输入框代理,监听 frame 变化
- 处理视图的添加和移除逻辑
- (void)configureAgentButton {
if (self.buttonAgent.superview) {
[self.buttonAgent removeFromSuperview];
}
[self.chatSessionInputBarControl.inputTextView.superview addSubview:self.buttonAgent];
CGSize size = self.chatSessionInputBarControl.inputTextView.superview.bounds.size;
CGFloat xOffset = self.chatSessionInputBarControl.inputTextView.frame.origin.x +self.chatSessionInputBarControl.inputTextView.frame.size.width;
self.buttonAgent.center = CGPointMake(xOffset-self.buttonAgent.frame.size.width/2-4, size.height/2);
UIEdgeInsets textEdge = self.chatSessionInputBarControl.inputTextView.textContainerInset;
textEdge.right += 22;
self.chatSessionInputBarControl.inputTextView.textContainerInset = textEdge;
}
- (void)chatInputBar:(RCChatSessionInputBarControl *)chatInputBar
shouldChangeFrame:(CGRect)frame {
[super chatInputBar:chatInputBar shouldChangeFrame:frame];
// 输入框还原, 则移除 AI 视图
if (chatInputBar.currentBottomBarStatus != KBottomBarPluginStatus) {
[self.agent.agentView removeFromSuperview];
return;
}
}
4. 实现代理方法
- 实现
RCAgentViewDelegate
协议方法,处理视图状态变化 - 实现
RCAgentFacadeDelegate
协议方法,处理推荐内容选择 - 实现数据源方法,获取历史消息
- (void)agentView:(RCAgentView *)agentView didMoveToSuperview:(UIView *)newSuperview {
if (newSuperview == nil) {
[self restoreInputBarFroAgent];
} else {
[self configureInputBarForAgent];
}
}
5. 展示 AI 会话页面
- 重载会话列表页面点击方法
- 创建并配置 AI 会话页面
- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType conversationModel:(RCConversationModel *)model atIndexPath:(NSIndexPath *)indexPath {
RCAIConversationViewController *vc = [[RCAIConversationViewController alloc] initWithConversationType:model.conversationType targetId:model.targetId];
RCConversationIdentifier *identifier = [[RCConversationIdentifier alloc] init];
identifier.targetId = model.targetId;
identifier.channelId = model.channelId;
identifier.type = model.conversationType;
RCAgentFacadeModel *agent = [[RCAgentFacadeModel alloc] initWithIdentifier:identifier delegate:vc];
vc.agent = agent;
[self.navigationController pushViewController:vc animated:YES];
}
注意事项
- 确保在使用前已经正确初始化了融云SDK
- 需要实现所有必要的代理协议来处理AI助手的交互
- 建议在适当的时机(如视图控制器销毁时)清理AI助手资源
- 可以根据需要自定义
customInfo
来调整AI助手的行为 - 运行App后,点击会话列表中的会话即可进入附带AI功能的会话页面
集成步骤
1. 创建自定义会话片段
- 创建一个新类
CustomConversationFragment
继承自ConversationFragment
- 关于如何创建和使用自定义会话页面,请参考会话页面文档
2. 重写 onViewCreated
方法并创建AI助手按钮
- 调用
super.onViewCreated(view, savedInstanceState)
保留父类功能 - 在私聊会话中创建
ImageView
作为AI助手按钮:Javaif (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);
示例代码
/**
* 自定义会话片段,继承自 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助手页面
- Android
- iOS
// 实现 RCAgentFacadeDelegate 代理方法
- (void)agent:(RCAgentFacadeModel *)agent
didSelectedRecommendations:(NSArray<RCAgentRecommendation *>*)recommendations {
for (RCAgentRecommendation *recommendation in recommendations) {
if ([recommendation imkit_category] == RCAgentRecommendationCategoryText) {
// 发送文本消息
RCTextMessage *textMessage = [RCTextMessage messageWithContent:recommendation.content];
[self sendMessage:textMessage];
}
}
// 清理智能体视图
[agent removeAndCleanAgentView];
}
// 实现数据源方法
- (void)agent:(RCAgentFacadeModel *)agent
fetchMessageWithIdentifier:(RCConversationIdentifier *)identifier
maxCount:(NSInteger)maxCount
completion:(void(^)(NSArray <RCAgentContextMessage *>* messages))completion {
// 获取历史消息
[[RCCoreClient sharedCoreClient] getHistoryMessages:identifier.type
targetId:identifier.targetId
objectNames:@[@"RC:TxtMsg"]
sentTime:0
isForward:YES
count:(int)maxCount
completion:^(NSArray<RCMessage *> * _Nullable messages) {
// 转换为上下文消息
NSMutableArray *contextMessages = [NSMutableArray array];
for (RCMessage *msg in messages) {
RCAgentContextMessage *contextMsg = [self convertToContextMessage:msg];
[contextMessages addObject:contextMsg];
}
completion(contextMessages);
}];
}
自定义 AgentFacadePage
通过继承AgentFacadePage
类创建自定义的AI助手页面:
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
:
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 请求推荐内容
- Android
- iOS
// 向智能体发起请求
[agentModel requestRecommendationWith:@"agentId"
customInfo:@{@"key": @"value"}];
// 向智能体发起请求 RongCoreClient#requestRecommendationWithParams
public abstract void requestRecommendationWithParams(
RequestRecommendationParams params,
IRongCoreCallback.RecommendationRequestCallback callback);