告别GPT-4!用通义千问Qwen-Plus快速上手AutoGen 0.5.7(附完整代码)

在AI技术日新月异的今天,开发者们面临着模型选择与成本优化的双重挑战。当OpenAI的GPT-4因其高昂的使用成本让许多开发者望而却步时,国产大模型通义千问Qwen-Plus以其出色的性能和亲民的价格逐渐崭露头角。本文将带你深入了解如何用Qwen-Plus替代GPT-4,快速上手AutoGen 0.5.7这一强大的多智能体开发框架。

1. 为什么选择Qwen-Plus替代GPT-4?

在开始技术实现之前,让我们先分析下这个替代方案的核心优势:

成本效益对比

指标 GPT-4 Qwen-Plus
每千token成本 $0.06(输入) ¥0.02(输入)
$0.12(输出) ¥0.02(输出)
响应速度 中等 快速
中文理解能力 优秀 卓越
API稳定性 受地域限制 国内稳定访问

从表格可以看出,Qwen-Plus在成本上具有明显优势,特别是对于中文场景的支持更为出色。更重要的是,它避免了国际API调用可能遇到的各种网络问题。

技术适配性分析

Qwen-Plus通过DashScope平台提供了与OpenAI兼容的API接口,这意味着:

  • 现有基于OpenAI的代码可以最小改动迁移
  • 不需要学习全新的SDK
  • 社区生态工具可以复用

2. 环境准备与基础配置

2.1 获取DashScope API密钥

  1. 访问阿里云DashScope官网并注册账号
  2. 进入控制台创建API密钥
  3. 记录下生成的sk-开头的密钥字符串

注意:API密钥是敏感信息,建议通过环境变量管理而非硬编码在脚本中。

2.2 安装必要依赖

确保Python版本≥3.10,然后执行:

pip install -U "autogen-agentchat" "autogen-ext[openai]"
pip install -U "autogenstudio"

对于需要网页浏览功能的场景,还需安装:

pip install playwright
playwright install

3. 核心代码适配实战

3.1 基础对话示例改造

以下是经典的Hello World示例,改造为使用Qwen-Plus:

# -*- coding: utf-8 -*-
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient

async def main() -> None:
    model_client = OpenAIChatCompletionClient(
        model="qwen-plus",
        api_key="your_api_key_here",  # 替换为你的AK
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        model_info={
            "vision": False,
            "function_calling": True,
            "json_output": True,
            "family": "unknown",
        }
    )
    agent = AssistantAgent("assistant", model_client=model_client)
    print(await agent.run(task="用中文说'你好世界'并解释这个编程传统"))
    await model_client.close()

asyncio.run(main())

关键适配点说明:

  1. model参数改为"qwen-plus"
  2. base_url指向DashScope兼容端点
  3. 根据Qwen特性设置model_info参数

3.2 网页浏览功能实现

下面展示如何让Qwen-Plus驱动的智能体进行网页信息检索:

# -*- coding: utf-8 -*-
import asyncio
from autogen_agentchat.agents import UserProxyAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.agents.web_surfer import MultimodalWebSurfer

async def main() -> None:
    model_client = OpenAIChatCompletionClient(
        model="qwen-plus",
        api_key="your_api_key_here",
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        model_info={
            "vision": False,
            "function_calling": True,
            "json_output": True,
            "family": "unknown",
        }
    )
    
    web_surfer = MultimodalWebSurfer(
        "web_surfer", 
        model_client, 
        headless=False,
        animate_actions=True
    )
    
    user_proxy = UserProxyAgent("user_proxy")
    termination = TextMentionTermination("exit", sources=["user_proxy"])
    team = RoundRobinGroupChat([web_surfer, user_proxy], termination_condition=termination)
    
    try:
        await Console(team.run_stream(
            task="查找最新的人工智能会议信息并总结关键点"
        ))
    finally:
        await web_surfer.close()
        await model_client.close()

asyncio.run(main())

常见问题排查

  • 如果遇到浏览器启动失败,确保已安装Playwright依赖
  • 网络请求超时可尝试调整timeout参数
  • 中文内容处理异常时检查编码设置

4. 高级应用:多智能体辩论系统

利用AutoGen的GroupChat功能,我们可以构建一个有趣的多智能体辩论系统:

# -*- coding: utf-8 -*-
import asyncio
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination

class DebateGroupChat(RoundRobinGroupChat):
    def __init__(self, agents, termination_condition):
        super().__init__(agents, termination_condition)
        self.current_agent_index = 0

    async def _select_next_speaker(self, messages):
        speaker = self.agents[self.current_agent_index]
        self.current_agent_index = (self.current_agent_index + 1) % len(self.agents)
        return speaker

async def main() -> None:
    model_client = OpenAIChatCompletionClient(
        model="qwen-plus",
        api_key="your_api_key_here",
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        model_info={
            "vision": False,
            "function_calling": True,
            "json_output": True,
            "family": "unknown",
        }
    )
    
    # 定义辩论角色
    host = AssistantAgent(
        name="host",
        model_client=model_client,
        system_message="你是一位专业辩论赛主持人,负责开场和流程控制。",
    )
    
    # 正方辩手
    pro_agents = [
        AssistantAgent(
            name=f"pro_{i}",
            model_client=model_client,
            system_message=f"你作为正方{i}辩,需用严谨逻辑支持'人性本善'观点。",
        ) for i in range(1, 5)
    ]
    
    # 反方辩手
    con_agents = [
        AssistantAgent(
            name=f"con_{i}",
            model_client=model_client,
            system_message=f"你作为反方{i}辩,需用有力论据反驳'人性本善'观点。",
        ) for i in range(1, 5)
    ]
    
    judge = AssistantAgent(
        name="judge",
        model_client=model_client,
        system_message="你是一位专业评委,需公正评价双方表现并给出胜负判断。",
    )
    
    agents = [host] + pro_agents + con_agents + [judge]
    termination = TextMentionTermination("最终判决")
    debate = DebateGroupChat(agents, termination_condition=termination)
    
    topic = input("请输入辩论主题:")
    await Console(debate.run_stream(task=f"关于'{topic}'的正式辩论"))
    
    await model_client.close()

asyncio.run(main())

这个实现展示了:

  1. 自定义GroupChat类控制发言顺序
  2. 多角色系统消息定制
  3. 中文辩论场景的流畅交互

5. AutoGen Studio可视化开发

对于偏好GUI的开发者,可以通过AutoGen Studio进行可视化配置:

  1. 启动服务:
autogenstudio ui --port 8080 --appdir ./my-app
  1. 访问http://localhost:8080

  2. 配置Qwen-Plus模型时使用JSON格式:

{
  "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",
  "component_type": "model",
  "config": {
    "model": "qwen-plus",
    "api_key": "your_api_key_here",
    "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
    "model_info": {
      "vision": "False",
      "function_calling": "True",
      "json_output": "True",
      "family": "unknown"
    }
  }
}

使用技巧

  • 通过Studio可以直观管理对话流程
  • 支持场景模板的保存与复用
  • 实时监控智能体交互过程

在实际项目中使用Qwen-Plus+AutoGen组合后,最明显的感受是成本的大幅降低,同时中文处理质量甚至优于GPT-4。特别是在需要频繁调用API的开发调试阶段,节省的费用相当可观。对于需要处理中文场景的AI应用开发者,这无疑是一个值得认真考虑的方案。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐