
理解 Autogen 与本地 LLM 集成
autogen 是一个强大的多智能体编程框架,它允许开发者通过配置不同的智能体来自动化复杂的任务。在使用 autogen 时,通常需要配置一个或多个大型语言模型(llm)作为智能体的“大脑”。除了使用 openai 的官方 api 外,autogen 也支持通过兼容 openai api 接口的本地 llm 服务(如 lm studio、ollama 等)进行集成。
典型的 Autogen 配置会使用 config_list 来定义 LLM 的连接参数,其中包括 api_base(API 端点地址)和 api_key(API 密钥,对于本地模型通常设为 "NULL" 或任意字符串)。在某些旧版本的 Autogen 中,为了明确指定 API 类型,还会包含 api_type 参数。
以下是一个常见的、可能导致问题的配置示例:
from autogen import AssistantAgent, UserProxyAgent
config_list = [
{
"api_type": "open_ai", # 导致错误的参数
"api_base": "http://localhost:1234/v1",
"api_key": "NULL"
}
]
llm_config = {'config_list': config_list}
assistant = AssistantAgent(
name="assistant",
llm_config = llm_config
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=100,
)
task = """write a python method to output numbers 1 to 100"""
user_proxy.initiate_chat(
assistant,
message=task
)当运行上述代码时,如果 Autogen 版本较新,可能会遇到以下错误:
TypeError: create() got an unexpected keyword argument 'api_type'
TypeError: create() got an unexpected keyword argument 'api_type' 错误分析
这个 TypeError 明确指出 create() 方法接收到了一个它不期望的关键字参数 'api_type'。从堆栈跟踪中可以看出,这个错误发生在 Autogen 内部调用 OpenAI 兼容客户端的 create 方法时。
错误发生的根本原因在于 Autogen 框架的演进。为了更好地与 OpenAI 官方 API 的最新版本保持兼容性,Autogen 团队在近期版本中对 LLM 配置方式进行了调整。其中一项重要的改变是移除了 config_list 中对 api_type 参数的显式要求或支持。
这意味着,当 Autogen 内部的 openai 客户端尝试处理 config_list 时,如果其中包含 api_type 参数,它会将其作为无效参数传递给底层的 openai.completions.create 或 openai.chat.completions.create 方法,从而导致 TypeError。
解决方案:移除 api_type 参数
解决此问题的方法非常直接:从 config_list 配置中移除 api_type 参数即可。由于 Autogen 已经默认将所有 config_list 中的配置视为兼容 OpenAI API 的格式,因此不再需要通过 api_type: "open_ai" 来显式声明。对于本地 LLM 服务,只要它们提供了兼容 OpenAI 接口的端点,Autogen 就能正确识别并使用。
以下是修正后的代码示例:
from autogen import AssistantAgent, UserProxyAgent
# 修正后的 config_list,移除了 "api_type" 参数
config_list = [
{
"api_base": "http://localhost:1234/v1", # LM Studio 等本地LLM服务的地址
"api_key": "NULL" # 本地LLM通常不需要API Key,设为"NULL"即可
}
]
llm_config = {'config_list': config_list}
assistant = AssistantAgent(
name="assistant",
llm_config = llm_config
)
user_proxy = UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=100,
)
task = """write a python method to output numbers 1 to 100"""
user_proxy.initiate_chat(
assistant,
message=task
)通过移除 api_type 参数,Autogen 将能够正确地解析配置,并使用本地 LLM 服务进行交互。
最佳实践与注意事项
- 保持 Autogen 更新: 遇到类似问题时,首先检查您使用的 Autogen 版本是否为最新。Autogen 作为一个活跃开发的开源项目,其 API 和内部实现会不断更新。通过 pip install --upgrade pyautogen 命令可以更新到最新版本。
- 查阅官方文档与更新日志: 遇到配置问题时,Autogen 的官方文档和 GitHub 仓库的发布说明(Release Notes)是解决问题的最佳资源。它们会详细说明任何破坏性变更(breaking changes)和新的配置选项。
- 兼容性: 确保您的本地 LLM 服务(如 LM Studio、Ollama 等)确实提供了与 OpenAI API 兼容的接口。大多数流行的本地 LLM 解决方案都旨在提供这种兼容性,但仍需确认其文档。
- 调试: 如果问题依然存在,可以尝试在 llm_config 中添加 verbose=True 来获取更详细的日志输出,这有助于定位问题。
总结
在使用 Autogen 框架集成本地 LLM 时,遇到 TypeError: create() got an unexpected keyword argument 'api_type' 错误,是由于 Autogen 版本更新后移除了 config_list 中 api_type 参数的支持。解决方案是简单地从配置中移除该参数。遵循本文提供的修正方法和最佳实践,可以帮助您更顺畅地在 Autogen 中利用本地 LLM 的强大能力,构建和运行多智能体应用。










