# python-qwen **Repository Path**: littlesquid_mc/python-qwen ## Basic Information - **Project Name**: python-qwen - **Description**: 将千问百炼平台的api接进python中,开箱即用 - **Primary Language**: Python - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-04-19 - **Last Updated**: 2026-05-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Python-Qwen 阿里云百炼平台 AI 对话客户端封装库,提供简洁易用的 Python 接口,支持纯文本和多模态对话功能。 ## ✨ 核心特性 - **简化集成**:封装 DashScope SDK,降低接入阿里云 AI 服务的门槛 - **多模态支持**:同时支持文本、图像和视频对话场景 - **灵活配置**:扁平化 YAML 配置系统,支持 30+ 可调参数 - **历史维护**:内置对话历史管理机制,便于构建连续对话应用 - **类型安全**:完整的类型注解,提升代码质量和开发体验 - **参数优先级**:运行时参数 > 配置文件 > API 默认值 ## 📦 安装 ### 环境要求 - Python 3.6+(推荐 3.8+) - 稳定的网络连接 ### 安装步骤 1. 克隆项目 ```bash git clone https://github.com/your-repository/python-qwen.git cd python-qwen ``` 2. 安装依赖 ```bash pip install -r requirements.txt ``` **依赖说明**: - `dashscope>=1.14.0`:阿里云百炼 SDK - `pyyaml>=6.0`:YAML 配置文件解析 ## 🔧 快速开始 ### 1. 配置 API 密钥 复制配置模板并编辑: ```bash cp config.yaml.example config.yaml ``` 编辑 `config.yaml`,填入你的 API 密钥: ```yaml dashscope: api_key: "YOUR_API_KEY_HERE" # 替换为你的实际 API Key model: "qwen-plus" # 使用的模型名称 multimodal: false # 是否使用多模态接口 # 对话参数配置(扁平化结构,直接配置参数) # 详情见 https://bailian.console.aliyun.com/cn-beijing?tab=api#/api/?type=model&url=3016809 chat: temperature: 0.7 # 采样温度 [0, 2) top_p: 0.8 # 核采样概率阈值 (0, 1.0] max_tokens: 2048 # 最大输出 Token 数 # 其他参数... ``` > ⚠️ **安全提示**:`config.yaml` 已加入 `.gitignore`,不会被提交到版本控制系统。 ### 2. 基础使用 #### 方式一:使用客户端类(推荐) ```python from ai_client import AIChatClient # 创建客户端实例 client = AIChatClient() # 单次对话 response = client.chat( prompt="请推荐今天随机菜谱", system_prompt="你是一位美食领域专家" ) print(f"AI回复:{response}") ``` #### 方式二:使用便捷函数 ```python from ai_client import chat # 快速对话 response = chat("你好,请介绍一下自己") print(response) ``` ### 3. 多模态对话 ```python from ai_client import AIChatClient # 创建客户端(需在 config.yaml 中设置 multimodal: true) client = AIChatClient() # 带图片的对话 response = client.chat( prompt="请描述这张图片", images=["https://example.com/image.jpg"], system_prompt="你是一位图像分析专家" ) print(f"AI回复:{response}") ``` ### 4. 连续对话 ```python from ai_client import AIChatClient client = AIChatClient() # 第一次对话 response1 = client.chat_with_history( prompt="请推荐今天的午餐菜单", system_prompt="你是一位营养师" ) print(f"AI回复1:{response1}") # 继续对话(自动维护历史) response2 = client.chat_with_history( prompt="能详细介绍一下这个菜品吗?" ) print(f"AI回复2:{response2}") # 清空历史 client.clear_history() ``` ## 📖 API 文档 ### AIChatClient 类 #### 初始化 ```python AIChatClient(config_path: Optional[str] = None) ``` **参数**: - `config_path`:配置文件路径(可选),默认为当前目录的 `config.yaml` **示例**: ```python # 使用默认配置 client = AIChatClient() # 显式指定配置路径 client = AIChatClient(config_path="/path/to/config.yaml") ``` #### chat() - 单次对话 ```python chat( prompt: str, history: Optional[List[Dict]] = None, system_prompt: Optional[str] = None, images: Optional[List[str]] = None, videos: Optional[List[str]] = None, **kwargs ) -> str ``` **参数**: - `prompt`:用户输入的问题/提示词 - `history`:对话历史(可选) - `system_prompt`:系统提示词,用于设定 AI 角色 - `images`:图片 URL 列表(多模态模型使用) - `videos`:视频 URL 列表(多模态模型使用) - `**kwargs`:运行时参数,可覆盖配置文件设置 **返回**:AI 的回复内容(字符串) #### chat_with_history() - 连续对话 ```python chat_with_history( prompt: str, system_prompt: Optional[str] = None, images: Optional[List[str]] = None, videos: Optional[List[str]] = None, **kwargs ) -> str ``` **参数**:与 `chat()` 相同,但不需要传入 `history` **特点**:自动维护和更新对话历史 #### clear_history() - 清空历史 ```python clear_history() ``` #### get_history() - 获取历史 ```python get_history() -> List[Dict] ``` **返回**:对话历史记录的副本 ### chat() 便捷函数 ```python chat( prompt: str, images: Optional[List[str]] = None, videos: Optional[List[str]] = None, config_path: Optional[str] = None, **kwargs ) -> str ``` 适用于简单的单次对话场景。 ## ⚙️ 配置说明 ### 配置结构 项目采用扁平化配置结构,`chat` 下的参数直接映射到 API 请求参数: ```yaml dashscope: api_key: "YOUR_API_KEY" # API 密钥 model: "qwen-plus" # 模型名称 multimodal: false # 多模态开关 chat: # 采样参数 temperature: 0.7 # 采样温度 [0, 2) top_p: 0.8 # 核采样概率阈值 (0, 1.0] top_k: null # 采样候选集大小 seed: null # 随机数种子 # 生成控制 max_tokens: 2048 # 最大输出 Token 数 stop: null # 停止词 stream: false # 是否流式输出 # 输出格式 response_format: null # 输出格式 (text/json_object) result_format: "message" # 返回数据格式 # 更多参数请参考 config.yaml.example ``` ### 参数优先级 1. **运行时参数**(最高):通过 `**kwargs` 传入 2. **配置文件参数**:`config.yaml` 中配置的参数 3. **API 默认值**(最低):DashScope API 的默认值 > 配置值为 `null` 的参数将被跳过,使用 API 默认值。 ### 环境变量 支持通过环境变量配置 API 密钥(优先级高于配置文件): ```bash # Windows set DASHSCOPE_API_KEY=your_api_key # macOS/Linux export DASHSCOPE_API_KEY=your_api_key ``` ## 💡 使用示例 ### 示例 1:JSON 格式输出 ```python from ai_client import AIChatClient client = AIChatClient() # 要求输出 JSON 格式 response = client.chat( prompt="请推荐今天随机菜谱以json格式输出", system_prompt="你是一位美食领域专家", response_format={"type": "json_object"} # 运行时覆盖 ) print(response) ``` ### 示例 2:批量处理 ```python from ai_client import AIChatClient client = AIChatClient() questions = [ "什么是机器学习?", "什么是深度学习?", "什么是强化学习?" ] for q in questions: response = client.chat(prompt=q) print(f"Q: {q}") print(f"A: {response}\n") ``` ### 示例 3:错误处理 ```python from ai_client import AIChatClient import time client = AIChatClient() try: response = client.chat("测试对话") print(response) except RuntimeError as e: print(f"API 调用失败:{e}") # 可以实现重试逻辑 ``` ## 🏗️ 项目结构 ``` python-qwen/ ├── ai_client.py # 核心客户端实现 ├── config.yaml # 运行时配置(已忽略) ├── config.yaml.example # 配置模板 ├── use.py # 使用示例 ├── requirements.txt # 依赖声明 ├── .gitignore # Git 忽略规则 └── README.md # 项目文档 ``` ## 🔍 常见问题 ### Q: 如何获取 API Key? 访问 [阿里云百炼平台](https://bailian.console.aliyun.com/) 注册并获取 API Key。 ### Q: 如何启用多模态功能? 1. 在 `config.yaml` 中设置 `multimodal: true` 2. 确保使用的模型支持多模态(如 qwen-vl-max) 3. 调用时传入 `images` 或 `videos` 参数 ### Q: 配置文件加载失败? - 检查 YAML 语法是否正确 - 确认文件编码为 UTF-8 - 验证文件路径是否正确 ### Q: 如何调整生成参数? 在 `config.yaml` 的 `chat` 部分配置: ```yaml chat: temperature: 0.9 # 更高的随机性 max_tokens: 4096 # 更长的输出 top_p: 0.95 # 更丰富的词汇 ``` ## 📝 最佳实践 1. **安全管理**:使用环境变量存储 API Key,避免硬编码 2. **参数调优**:根据应用场景调整 `temperature`、`max_tokens` 等参数 3. **历史管理**:定期调用 `clear_history()` 释放内存 4. **错误处理**:实现适当的重试和异常处理机制 5. **性能优化**:批量请求时复用客户端实例 ## 📚 参考资源 - [阿里云百炼平台官方文档](https://bailian.console.aliyun.com/cn-beijing?tab=api#/api/?type=model&url=3016809) - [DashScope SDK 文档](https://help.aliyun.com/zh/dashscope/) - [通义千问模型列表](https://help.aliyun.com/zh/dashscope/developer-reference/model-introduction) ## 🤝 贡献 欢迎提交 Issue 和 Pull Request! ## 📄 许可证 [MIT License](LICENSE) ## 📮 联系方式 如有问题或建议,请通过以下方式联系: - 提交 Issue - 发送邮件littlesquid@163.com --- **Enjoy AI Development with Python-Qwen! 🚀**