一文傻瓜式教你通过X-AIO平台创建自己本地对话的私人智能体。

26 阅读2分钟

本篇文章主要讲解通过三方聚合平台实现ai智能体交互的编程教程。 日期:2026年3月8日 作者:任聪聪

材料准备

获取X-AIO账号

打开官网:www.x-aio.com/ 点击登录进行注册即可。 file 进入后填写邮箱及基本信息即可注册。

创建密钥在这里插入图片描述

在个人中心账号管理部分找到如下菜单。 file 点击新建 file 选择类型: file 创建完毕后,复制自己的密钥复制到下面的代码实例对应处即可。

代码实例

import requests
import json
import threading
import time

def show_loading_indicator(stop_event):
    """显示动态加载提示"""
    symbols = ["|", "/", "-", "\\"]
    idx = 0
    while not stop_event.is_set():
        print(f"\rAI正在思考中... {symbols[idx % len(symbols)]}", end="", flush=True)
        idx += 1
        time.sleep(0.2)
    print("\r", end="")  # 清除加载提示

def chat_with_ai():
    url = "https://api.x-aio.com/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer 你的密钥"  # 替换为您的实际API密钥
    }

    # 获取用户自定义的角色设定
    role_hint = input("请输入角色设定(例如:你是一个幽默的诗人,直接回车跳过): ").strip()
    if not role_hint:
        role_hint = "你是一个乐于助人的助手。"

    print("AI聊天机器人(输入'exit'退出):")

    while True:
        user_input = input("你: ")

        if user_input.lower() == "exit":
            print("再见!")
            break

        body = {
            "model": "Qwen3-30B-A3B-Instruct-2507",
            "messages": [
                {
                    "role": "system",
                    "content": role_hint  # 使用用户自定义的角色设定
                },
                {
                    "role": "user",
                    "content": user_input
                }
            ],
            "top_k": 0,
            "min_p": 0,
            "stream": True  # 启用流式传输
        }

        try:
            # 启动加载提示线程
            stop_loading = threading.Event()
            loading_thread = threading.Thread(target=show_loading_indicator, args=(stop_loading,))
            loading_thread.start()

            with requests.post(url, json=body, headers=headers, stream=True) as response:
                response.raise_for_status()  # 对HTTP错误引发异常
                stop_loading.set()  # 停止加载提示
                loading_thread.join()  # 等待提示线程结束

                print("AI: ", end="", flush=True)

                # 逐行处理流式响应
                for line in response.iter_lines():
                    if line:
                        decoded_line = line.decode("utf-8")
                        if decoded_line.startswith("data: "):
                            data = decoded_line[6:]  # 移除"data: "前缀
                            if data.strip() == "[DONE]":
                                break  # 流结束
                            try:
                                # 解析JSON块
                                chunk_data = json.loads(data)
                                choices = chunk_data.get("choices", [])
                                if choices:
                                    delta = choices[0].get("delta", {})
                                    content = delta.get("content", "")
                                    if content:
                                        print(content, end="", flush=True)
                            except (json.JSONDecodeError, IndexError):
                                pass  # 忽略无效的JSON或缺失数据
                print()  # 完整响应后换行
        except Exception as e:
            stop_loading.set()  # 出现异常时停止加载提示
            loading_thread.join()
            print(f"\n错误: {e}")

if __name__ == "__main__":
    chat_with_ai()

保存文件名为cmdAI.py,同时记得通过pip安装对应的依赖,如下。

pip install requests

代码效果

file