暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

大模型服务公测中,创建自己的多模态 AI 应用!

青云QingCloud 2024-12-28
151

青云科技旗下 AI 算力云服务——基石智算正式推出大模型服务平台,现已开启公测啦!公测阶段,接口调用限时免费。

AI 发展日新月异,但在模型相关的应用过程中,总会遇到各种各样的难题,比如怎么高效管理 AI 模型资源,又或者在模型训练、部署与优化时困难重重。不过别担心,大模型服务平台就是帮大家解决这些问题的。

基石智算大模型服务平台是一个专为开发者设计的高效、灵活、稳定、易用的综合性大模型服务平台,旨在提供便捷、高效、快速体验的大模型服务,同时支持开发者制作全新应用或集成现有应用。该平台致力于简化大模型技术的使用门槛,让每一位开发者都能轻松利用前沿人工智能技术推动项目的创新与发展。


全方位助力 AI 应用开发


基石智算大模型服务平台打造开箱即用的大模型推理服务,不仅具备高度的灵活性和可扩展性,能够满足不同开发者的多样化需求。同时,不同模型接口提供不同计量方式,如语音生成本文用秒,对话模型是按照 token 数计费,不仅更合理,而且更加清晰明了,有助于开发者更好地控制成本。
平台为开发者提供丰富的模型资源,包括文本生成、语音识别、语音合成以及 Embedding 服务等。同时,平台还兼容 OpenAI 接口规范,使得用户可以直接调用相应的模型 API,无需进行复杂的接口适配工作,极大地提升了开发效率和用户体验。
后续将有更多模型资源上线,满足不同开发者在各种 AI 应用开发场景下的多样需求。用户可以根据自己的项目特点和功能要求,灵活选用合适的模型助力开发。
另外,大模型服务平台的一大亮点就是兼容 OpenAI 接口规范,这对于广大开发者来说,是实实在在的便利之举。
此外,大模型服务平台还配备了稳定的后端服务,确保服务的持续性和可靠性。

申请 API Key,开启应用接入

对于想要接入大模型服务平台并使用其功能的开发者们,申请 AI API Key 是关键的一步,下面就为大家呈现操作步骤:
1.  登录基石智算控制台,在顶部导航栏中,选择“产品与服务” - “大模型服务” - “API 密钥管理”。
2.  点击“创建 API 密钥”,输入 API 密钥别名,点击确定即可。
新建的密钥将显示在相应的列表内,将鼠标悬停在指定密钥上,点击 API 密钥右侧的复制按钮,即可获取完整的 API 密钥。


最佳实践,打造智能语音助手


本次实践中,打造一个智能语音助手应用,就像日常使用的智能音箱一样,可以实现语音交互。具体来说,它通过调用三个关键接口,也就是 “语音转文字”、“文生文” 以及 “文字转语音” 来达成这样的交互效果。

代码运行后,会提示输入一段语音,程序采集到语音后调用“语音转文字”接口,识别出文字结果并打印到控制台。然后调用大语言模型生成会话回复(支持多轮会话),把回复内容打印到控制台,同时调用“文字转语音”接口,就可以把合成出来的语音朗读出来。完成这一轮交互后,就会进入下一次循环。

 步骤:

1. 替换代码中 api_key 变量为实际 API 密钥,代码内容保存到文件 audio_robot.py。
代码文件下载链接:https://aicpfile.pek3b.qingstor.com/audio_robot.py
    # -*- coding: utf-8 -*-
    import os
    import io
    import threading
    import time
    import wave
    import queue
    import random


    import pygame
    import pyaudio
    from openai import OpenAI




    client = OpenAI(api_key='sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', base_url='https://openapi.coreshub.cn/v1' )


    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 16000
    CHUNK = 1024


    def clear_and_print(content):
    content = content.replace('\n', '')
    print(f'\r{content}', end='', flush=True)


    def truncate_to_last_sentence(text):
    last_punct = max(text.rfind('!'), text.rfind('。'), text.rfind('?'))
    if last_punct != -1:
    return text[:last_punct + 1]
    return text


    class AudioRecorder:
    """
    录音机
    """
    def __init__(self):
    self.audio = pyaudio.PyAudio()
    self.stream = None
    self.frames = []
    self.is_recording = False


    def start_recording(self):
    self.is_recording = True
    self.frames = []
    print("[系统] 输入任意键开始录音,退出请按'q'")
    if input() == 'q':
    print('[系统] 再见!')
    exit(0)
    self.stream = self.audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True,
    frames_per_buffer=CHUNK, stream_callback=self.callback)
    self.stream.start_stream()
    print("[系统] 开始录音,任意键结束录音...")


    def stop_recording(self):
    if self.stream:
    self.stream.stop_stream()
    self.stream.close()
    self.stream = None
    self.is_recording = False
    print("[系统] 录音结束.")
    return self.save_audio()


    def save_audio(self):
    filename = f"recording_{int(time.time())}.wav"
    wf = wave.open(filename, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(self.audio.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(self.frames))
    wf.close()
    return filename


    def callback(self, in_data, frame_count, time_info, status):
    if self.is_recording:
    self.frames.append(in_data)
    return (in_data, pyaudio.paContinue)


    def listen(self):
    self.start_recording()
    try:
    input()
    except KeyboardInterrupt:
    pass
    finally:
    return self.stop_recording()


    def __del__(self):
    if self.stream:
    self.stream.stop_stream()
    self.stream.close()
    self.audio.terminate()




    class AudioPlayer:
    def __init__(self):
    self.text_queue = queue.Queue()
    self.audio_data_queue = queue.Queue()
    self.is_playing = False
    pygame.mixer.init()
    threading.Thread(target=self._request_audio_thread, daemon=True).start()
    threading.Thread(target=self._play_audio_thread, daemon=True).start()


    def add_to_queue(self, text):
    self.text_queue.put(text)


    def _request_audio_thread(self):
    while True:
    text = self.text_queue.get()
    response = client.audio.speech.create(model='CosyVoice-300M', voice='中文女', input=text)
    audio_data = io.BytesIO(response.content)
    self.audio_data_queue.put(audio_data)
    self.text_queue.task_done()


    def _play_audio_thread(self):
    while True:
    audio_data = self.audio_data_queue.get()
    self._play_audio(audio_data)
    time.sleep(0.8 + 0.1 * abs(random.random()))
    self.audio_data_queue.task_done()


    def _play_audio(self, audio_data):
    self.is_playing = True
    pygame.mixer.music.load(audio_data)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
    pygame.time.Clock().tick(10)
    self.is_playing = False


    def stream_chat_response(messages):
    response = client.chat.completions.create(model="Qwen2-0.5B-Instruct", messages=messages, stream=True)
    full_text = ""
    for chunk in response:
    if len(chunk.choices) and chunk.choices[0].delta.content:
    new_content = chunk.choices[0].delta.content
    full_text += new_content
    yield new_content, full_text


    def clean_text(text):
    text = text.replace("\n", "")
    text = text.replace("*", "")
    return text


    recorder = AudioRecorder()
    audio_player = AudioPlayer()
    history = []
    print('[系统] 开始对话')
    while True:
    audio_file = recorder.listen()


    # ------------------------------------------------------------------------------------------------
    print('ASR 推理中...')
    with open(audio_file, 'rb') as file:
    response = client.audio.transcriptions.create(file=file, model='SenseVoiceSmall')
    os.remove(audio_file)
    question_txt = response.text
    print("> 问题: ", question_txt)


    # ------------------------------------------------------------------------------------------------
    messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    *[{"role": "user" if i % 2 == 0 else "assistant", "content": msg} for i, msg in enumerate(sum(history, ()))],
    {"role": "user", "content": question_txt}
    ]
    full_text = ""
    audio_chunk = ""
    for new_content, full_text in stream_chat_response(messages):
    clear_and_print(f'< 回答: {full_text}')
    audio_chunk += new_content


    if ('!' in audio_chunk or '?' in audio_chunk or '。' in audio_chunk) and len(audio_chunk) > 55:
    truncated_chunk = truncate_to_last_sentence(audio_chunk)
    if truncated_chunk:
    cleaned_chunk = clean_text(truncated_chunk)
    audio_player.add_to_queue(cleaned_chunk)
    audio_chunk = audio_chunk[len(truncated_chunk):]
    print()
    if audio_chunk:
    truncated_chunk = truncate_to_last_sentence(audio_chunk)
    if truncated_chunk:
    audio_player.add_to_queue(truncated_chunk)
    if len(audio_chunk) > len(truncated_chunk):
    audio_player.add_to_queue(audio_chunk[len(truncated_chunk):])


    history.append((question_txt, full_text))
    history = history[-8:]


    audio_player.text_queue.join()
    audio_player.audio_data_queue.join()
    2. 执行和测试应用
      # 安装依赖
      pip install pygame pyaudio openai
      python audio_robot.py

       示例:

      总之,AI 应用开发者可以很方便地通过 OpenAI 标准的依赖库使用大模型服务平台服务,实现构建“多模态”应用。
      希望不同行业、不同背景的开发者们,都能在大模型服务平台上找到适合自己的创新切入点,将 AI 技术深度融入到各个具体场景中,推动 AI 在各领域真正落地并蓬勃发展。

      大模型服务平台现已开启公测
      限时免费的接口调用机会就在眼前
      大家可千万别错过,快来体验吧!




       相关链接 

      平台直通地址:https://console.coreshub.cn/xb2/maas/global-markets
      API 接口地址:https://openapi.coreshub.cn/v1/models
      接口文档地址:https://docs.coreshub.cn/console/big_model_server


      - FIN -

      更多推荐



      点击“阅读原文”了解更多

      文章转载自青云QingCloud,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

      评论