Flutter集成Mistral AI服务插件mistralai_client_dart_flutter_flow的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter集成Mistral AI服务插件mistralai_client_dart_flutter_flow的使用

本教程将介绍如何在Flutter项目中集成Mistral AI服务插件mistralai_client_dart_flutter_flow。通过该插件,您可以轻松地调用Mistral AI的各种API功能。


插件描述

mistralai_client_dart_flutter_flow 是一个非官方的Dart/Flutter客户端库,用于与Mistral AI API进行交互。该实现受到官方Mistral AI JavaScript客户端的启发。


使用场景

支持版本

  • FlutterFlow: 4.1
  • Flutter: 3.13.7+

安装

在您的pubspec.yaml文件中添加以下依赖项:

dependencies:
  mistralai_client_dart_flutter_flow: ^最新版本号

然后运行以下命令以安装依赖:

dart pub get

基本使用

创建客户端

首先,导入插件并创建一个MistralAIClient实例:

import 'package:mistralai_client_dart_flutter_flow/mistralai_client_dart_flutter_flow.dart';

// 替换为您的API密钥
final client = MistralAIClient(apiKey: 'your_api_key_here');

列出模型

使用listModels方法获取可用的Mistral AI模型列表:

final modelsResult = await client.listModels();
final models = modelsResult.data.map((e) => e.id).toList();
print(models.join(', ')); // 输出模型ID列表

聊天功能

使用chat方法与Mistral AI进行对话:

final params = ChatParams(
  model: 'mistral-small-latest',
  messages: const [
    ChatMessage(role: 'user', content: 'Hello chat!'),
  ],
);

final chatCompletion = await client.chat(params);
final chatMessage = chatCompletion.choices[0].message;
print(chatMessage); // 输出AI回复

流式聊天

如果您希望实时接收AI的回复,可以使用streamChat方法:

final stream = client.streamChat(params);
await for (final completionChunk in stream) {
  final chatMessage = completionChunk.choices[0].delta?.content;
  if (chatMessage != null) {
    print(chatMessage); // 实时打印AI的逐段回复
  }
}

获取嵌入向量

使用embeddings方法生成文本嵌入向量:

final embeddings = await client.embeddings(
  const EmbeddingParams(
    model: 'mistral-embed',
    input: ['Hello chat!'],
  ),
);

for (final data in embeddings.data) {
  print(data.embedding); // 输出嵌入向量
}

函数调用

如果需要调用外部函数,可以配置tools参数:

String retrievePaymentStatus(Map<String, String> data, String transactionId) =>
    '{"status": ${data[transactionId]}}';

final namesToFunctions = {
  'retrievePaymentStatus': (String transactionId) =>
      retrievePaymentStatus(paymentStatusData, transactionId),
};

final tools = [
  const ToolsFunction(
    name: 'retrievePaymentStatus',
    description: 'Get payment status of a transaction',
    parameters: [
      ToolsFunctionParameter(
        name: 'transactionId',
        type: 'string',
        description: 'The transaction ID',
        isRequired: true,
      ),
    ],
  ).toChatParamsFormat(),
];

var chatResponse = await client.chat(
    ChatParams(
        model: 'mistral-large-latest',
        messages: messages,
        tools: tools,
        toolChoice: 'auto',
    ),
);

final toolCall = chatResponse.choices[0].message.toolCalls?[0];
if (toolCall != null && toolCall.type == 'function') {
    final functionName = toolCall.function!.name;
    final functionParams = toolCall.function!.argumentsMap;

    print('calling functionName: $functionName');
    print('functionParams: $functionParams');

    final functionResult = namesToFunctions[functionName]!(
        functionParams['transactionId']! as String,
    );

    messages.add(
        ChatMessage(role: 'tool', content: functionResult, name: functionName),
    );

    chatResponse = await client.chat(
        ChatParams(
            model: model,
            messages: messages,
            tools: tools,
            toolChoice: 'auto',
        ),
    );

    print(chatResponse.choices[0].message.content);
}

示例完整代码

以下是一个完整的Flutter示例,展示了如何集成mistralai_client_dart_flutter_flow插件并使用其核心功能:

import 'package:flutter/material.dart';
import 'package:mistralai_client_dart_flutter_flow/mistralai_client_dart_flutter_flow.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  [@override](/user/override)
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final client = MistralAIClient(apiKey: 'your_api_key_here');
  String response = '';

  Future<void> listModels() async {
    final modelsResult = await client.listModels();
    final models = modelsResult.data.map((e) => e.id).toList();
    setState(() {
      response = models.join(', ');
    });
  }

  Future<void> chat() async {
    final params = ChatParams(
      model: 'mistral-small-latest',
      messages: const [
        ChatMessage(role: 'user', content: 'Hello chat!'),
      ],
    );

    final chatCompletion = await client.chat(params);
    setState(() {
      response = chatCompletion.choices[0].message.content;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mistral AI Client Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: listModels,
              child: Text('List Models'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: chat,
              child: Text('Start Chat'),
            ),
            SizedBox(height: 20),
            Text(response),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter集成Mistral AI服务插件mistralai_client_dart_flutter_flow的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter集成Mistral AI服务插件mistralai_client_dart_flutter_flow的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


要在Flutter项目中集成Mistral AI服务,并使用mistralai_client_dart_flutter_flow插件,你可以按照以下步骤进行操作:

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加mistralai_client_dart_flutter_flow插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  mistralai_client_dart_flutter_flow: ^0.1.0  # 请使用最新版本

然后运行flutter pub get来获取依赖。

2. 初始化Mistral AI客户端

在你的Flutter项目中,初始化Mistral AI客户端。你需要在main.dart或其他适当的地方进行初始化。

import 'package:mistralai_client_dart_flutter_flow/mistralai_client_dart_flutter_flow.dart';

void main() {
  // 初始化Mistral AI客户端
  MistralAIClient.initialize(apiKey: 'YOUR_API_KEY');
  
  runApp(MyApp());
}

确保将YOUR_API_KEY替换为你的Mistral AI API密钥。

3. 使用Mistral AI服务

你可以在你的应用中使用Mistral AI服务。以下是一个简单的示例,展示如何调用Mistral AI的文本生成功能。

import 'package:flutter/material.dart';
import 'package:mistralai_client_dart_flutter_flow/mistralai_client_dart_flutter_flow.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Mistral AI Example'),
        ),
        body: Center(
          child: TextButton(
            onPressed: () async {
              // 调用Mistral AI的文本生成服务
              String prompt = "Once upon a time";
              String generatedText = await MistralAIClient.generateText(prompt);
              print(generatedText);
            },
            child: Text('Generate Text'),
          ),
        ),
      ),
    );
  }
}

4. 处理响应

在上面的示例中,MistralAIClient.generateText方法会返回生成的文本。你可以根据需要处理这个响应,例如将其显示在UI中。

5. 错误处理

在实际应用中,你可能需要处理网络请求中的错误。你可以使用try-catch块来捕获和处理异常。

onPressed: () async {
  try {
    String prompt = "Once upon a time";
    String generatedText = await MistralAIClient.generateText(prompt);
    print(generatedText);
  } catch (e) {
    print('Error: $e');
  }
},
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!