RAG LLM代理:解决固体力学和流体动力学问题

2024年08月06日 由 alex 发表 130 0

1


展望未来,人工智能将通过简单的对话毫不费力地解决工程问题。下一代人工智能和语言模型将彻底改变我们利用有限元分析 (FEA) 和计算流体动力学 (CFD) 等工程工具解决结构分析、热力学、空气动力学、电场和电磁势等复杂问题的方式。很快,掌握这些工具将不再需要用户具备机械、数学、材料、物理或编程方面的丰富专业知识。


如今的大型语言模型(LLM)和生成式人工智能工具可以模仿人类行为,如自然语言处理、模式识别、记忆保持、批判性思维、推理和决策。它们还能用 C++、Python、Julia 和 MATLAB 编写和调试数值算法。除了语言之外,他们还是会话式人工智能代理背后的大脑,使人工智能与人类和人工智能与工具之间的互动更加顺畅和有效。多个代理可以协作计划和执行任务、监控输出、适应和使用工具,以自主实现目标。通过将这些能力结合起来,工程师很快就能与强大的数值模拟工具进行交互,并通过对话解决工程问题,只需最少的干预。


在这些进展的基础上,我将在本文中演示如何构建一个由 LLM 驱动的人工智能代理网络,该网络可以自主创建模型并模拟固体力学和流体动力学问题,而只需极少的人工输入。我们使用 Microsoft AutoGen 建立了一个会话代理团队,每个代理都是规划、问题提出、编写、调试和执行代码、绘图和分析以及结果评论等方面的专家。它们将自主工作,根据需要相互纠正,使用开源 Python 库创建和模拟有限元分析和 CFD 模型。OpenAI 的 GPT-4 是这背后的动力源。该框架通过 Chainlit 应用程序封装在用户界面中。


以下是该应用程序的实际运行情况。


2


示例和提示

我在各种二维有限元分析和 CFD 问题(标注为(a)-(d))以及一个三维有限元分析问题(标注为(e))上测试了该应用程序。下面是代理生成的相应图形以及初始用户提示。


3


以下是我在上述五个示例中使用的提示。


a) 位移下的二维板

一块 1 米乘 1 米的弹性板的杨氏模量为 1GPa,泊松比为 0.3。左侧边缘的位移为零,右侧边缘沿 x 方向的位移为 0.1 米。使用 FENICS 求解位移,并将位移结果存储在 PNG 文件中。


b) 带圆孔的板处于位移状态

一块二维板占据一个 1 米乘 1 米的区域。它由铜制成,中间有一个半径为 0.2 米的圆孔。它的左边缘位移为零,右边缘沿 x 方向位移为 0.02 米。上下边缘可自由移动。请使用 FENICS 求解位移,绘制并将 von Misses 应力存储在 PNG 文件中,并计算出右侧边缘的总力。


c) 流经矩形通道的二维不可压缩流体流动

求解长 2 米、高 0.5 米的矩形通道内的二维不可压缩流体流动。流体密度为 1,粘度为 0.001。在左侧入口处规定了一个完全展开的抛物线速度曲线,最大速度 = 0.3。使用 FEniCS FE python 库求解二维压力场和速度场。绘制压力场图,并将图保存为 PNG 文件。


d) 流经带有圆形障碍物的矩形通道的二维流动

求解在长 2 米、高 0.5 米的矩形水道内圆柱体上的二维不可压缩流体流动。圆柱体以 (0.2m, 0.2m) 为中心,直径为 0.1m。流体密度为 1,粘度为 0.001。在左侧入口处规定了一个完全展开的抛物线速度曲线,最大速度 = 0.3。使用 FEniCS FE python 库求解二维压力场和速度场。绘制压力场图,并将图保存为 PNG 文件。


e) 内压下的三维空心钢管

创建外径为 5 毫米、壁厚为 0.5 毫米的三维钢管网格。首先绘制网格图并与用户验证。使用 FEniCS FE python 库求解钢管在 100 兆帕内压作用下的位移。使用 Pyvista 绘制并显示三维位移。将绘图保存为 PNG 文件。


请注意,这些都不是立竿见影的解决方案。有时,我需要与代理进行多次来回对话,反复推敲,直到把问题解决为止。例如,问题(b)涉及一个中央有圆孔的板。起初,几何图形中缺少了这个孔,但经过几次反复后,我们修正了它。同样,CFD 问题缺少一个圆形障碍物,我们通过调试解决了这个问题。三维问题需要的反复次数最多,包括关闭并重新打开应用程序从头开始。我还调整了输入提示,以便更好地引导模型开发过程。总的来说,我对结果非常满意。这只是 LLM 驱动的代理为建模和仿真任务编写、调试和执行工程代码的开始。


开发是在 Linux 环境中使用 Windows Subsystem for Linux (WSL) 和 Visual Studio Code 在 Windows 11 PC 上完成的,该 PC 配备英特尔 i9 13 代处理器、64 GB 内存和 24 GB Nvidia RTX 4090。我还没有在本机 Windows 环境中进行过测试,但请放心。


安装指南

本实施方案的核心是让人工智能代理能够利用开源 Python 库和工具。要解决有限元分析或 CFD 问题,我们需要一些工具来编写几何脚本、使用数值算法进行求解并将结果可视化。gmsh 是一个三维有限元网格生成器,具有内置的预处理和后处理功能。FEniCS 是一个用于求解偏微分方程 (PDE) 的开源计算平台,可用于制定和运行数值模拟。在可视化方面,二维几何图形使用 matplotlib,三维几何图形使用 pyvista。其他所需库列于 GitHub 仓库中的 requirements.txt 文件中。


在创建应用程序时,我只安装了 AutoGen 和 Chainlit。通常情况下,代理可以根据你要求它们解决的问题自动安装所有其他必要的库。不过,这通常会消耗额外的令牌和 API 调用,有时还会无法高效工作。因此,我预先安装了这些库,因为我知道需要它们。


请记住,你需要从 ChatGPT 获取 GPT-4o 的 API 密钥。如果硬件条件允许,你可以尝试使用像 Llama3:405B 这样的离线模型。较小的机型还不能使用。


安装和启动应用程序的终端命令

从 conda-forge 频道安装 FEniCS 也会安装兼容的 Python 版本,所以我们不需要指定。


# Create conda environment and install FEniCS FEA package
conda create -n fea_agents -c conda-forge fenics mshr
# Activate environment
conda activate fea_agents
# Clone github repo
git clone https://github.com/karthik-codex/autogen_FEA.git
# select current directory
cd autogen_FEA
# Install other python packages (AutoGen, Chainlit, matplotlib, numpy, etc..)
pip install -r requirements.txt
# Export OpenAI API key
export API_KEY=<your_key_xxxxxx>
# Run chainlit app on default port - http://localhost//8000
chainlit run appUI.py


  1. ./requirements.txt- 包含上述所有软件包的列表
  2. ./chainlit_agents.py- 包含 AutoGen 的助手和用户代理的类定义。这样就可以跟踪多个代理,并在用户界面中显示它们的信息。(感谢 Chainlit 团队构建该模板)。
  3. ./appUI.py-包含主要的异步函数,用于设置代理、跟踪和处理消息,并在 Chainlit UI 中显示。


主要 Python 应用程序分解


导入库

你会发现 chainlit_agents 中导入了两个类。这些 AutoGen 代理的封装类能让 Chainlit 跟踪它们的对话,以正确的格式显示文本和代码,并处理终止或其他用户输入。


import os
import autogen
import chainlit as cl
from chainlit_agents import ChainlitUserProxyAgent, ChainlitAssistantAgent


加载 LLM 配置

将 API 密钥导出到操作系统环境中,或将其作为字符串变量直接粘贴到代码中。


api_key = os.getenv('API_KEY')
config_list_openai = [
    {"model": "gpt-4o", "api_key": api_key}
]
llm_config = {
    "seed": 565,  # change the seed for different trials
    "temperature": 0,
    "config_list": config_list_openai,
    "timeout": 60000,
}


为代理创建系统信息。

我们设计了具有特定角色的代理:管理员(admin)、规划员、科学家、工程师、执行者、评论员和群聊管理员,并将他们组织成一个研究小组,进行自主、互动和动态的群聊。每个代理的角色都是通过代理剖析来定义的,利用初始提示来影响 LLM 在聊天过程中的行为。


  1. 管理员分配任务,并在被问及时提供见解。
  2. 规划员制定分步计划,并为其他代理建议具体的子任务。
  3. 科学家使用有限元法制定力学问题。
  4. 工程师编写并调试执行代码。
  5. 执行者运行脚本,访问模拟环境并共享结果。
  6. 评论员对过程和代理的表现进行评估。
  7. 群聊管理器通过选择发言人、收集输入信息和广播消息来协调对话。


以下是每个代理的系统提示。


USER_PROXY_MESSAGE = '''A human admin. Interact with the planner to discuss the plan. 
Plan execution needs to be approved by this admin.'''
ENGINEER_MESSAGE = '''Engineer. You follow an approved plan. You write Python/shell code to solve tasks. 
Wrap the code in a code block that specifies the script type. The user can't modify your code. 
So do not suggest incomplete code which requires others to modify. Don't use a code block if it's 
not intended to be executed by the executor. Don't include multiple code blocks in one response. 
Do not ask others to copy and paste the result. Check the execution result returned by the executor. 
If the result indicates there is an error, fix the error and output the code again. 
Suggest the full code instead of partial code or code changes. If the error can't be fixed or if 
the task is not solved even after the code is executed successfully, analyze the problem, 
revisit your assumption, collect additional info you need, and think of a different approach to try.
In the code you write, always add a part to report the solution on the boundaries and store it in a separate file for the Scientist to check.'''
PLANNER_MESSAGE = """Planner. Suggest a plan. Revise the plan based on feedback from admin and critic, until admin approval.
The plan may involve an engineer who can write code and a scientist who doesn't write code.
Explain the plan first. Ask the Executor to install any Python libraries or modules as needed without human input. 
Be clear which step is performed by an engineer, and which step is performed by a scientist."""
SCIENTIST_MESSAGE = """Scientist. You follow an approved plan. You can formulate the mechanics problem with 
clear boundary conditions and constitutive law of materials. You don't write code. You explicitly check the 
boundary results from the Engineer to see whether it agrees with the input boundary conditionand geometry. 
When you execute the code, always save a copy for review."""
EXECUTOR_MESSAGE = """Executor. Save and execute the code written by the engineer and report and save the result. 
Use both shell and python language interpreter."""
CRITIC_MESSAGE = """ Critic. Double check plan, claims, code from other agents, results on the boundary conditions, and provide feedback. 
Check whether the plan includes adding verifiable info such as source URL."""


Chainlit UI 的启动功能。

我们会在用户打开聊天应用程序并打印欢迎信息时创建代理。执行器运行脚本,访问模拟环境并共享结果。因此,我们启用了代码执行配置,并将 docker 设置为 False,以便仅使用本机操作系统环境执行代码。


@cl.on_chat_start
async def on_chat_start():
  try:
    print("Set agents.")
    user_proxy  = ChainlitUserProxyAgent("Admin", system_message=USER_PROXY_MESSAGE, code_execution_config=False)
    engineer    = ChainlitAssistantAgent("Engineer", llm_config=llm_config, system_message=ENGINEER_MESSAGE)
    scientist   = ChainlitAssistantAgent("Scientist", llm_config=llm_config, system_message=SCIENTIST_MESSAGE)
    planner     = ChainlitAssistantAgent("Planner",llm_config=llm_config, system_message=PLANNER_MESSAGE)
    critic      = ChainlitAssistantAgent("Critic", llm_config=llm_config, system_message=CRITIC_MESSAGE)
    executor    = ChainlitAssistantAgent("Executor", system_message=EXECUTOR_MESSAGE, human_input_mode="NEVER",
                                    code_execution_config={"last_n_messages": 3, "work_dir": "FEA_results","use_docker": False})    
    cl.user_session.set("user_proxy", user_proxy)
    cl.user_session.set("engineer", engineer)
    cl.user_session.set("scientist", scientist)
    cl.user_session.set("planner", planner)
    cl.user_session.set("critic", critic)
    cl.user_session.set("executor", executor)
    msg = cl.Message(content=f"""Hello! What simulation task would you like to get done today?      
                     """, 
                     author="User_Proxy")
    await msg.send()
    
  except Exception as e:
    print("Error: ", e)
    pass


对话功能

为了测试这个多机器人小组自主解决工程问题的能力,我们仅使用管理代理(用户代理)来分配任务。虽然可以在不同阶段收集人工输入,但我们在群组聊天时跳过了人工输入。你可以根据要解决的问题的复杂程度,增加变量 MAX_ITER,以增加代理之间的对话。


@cl.on_message
async def run_conversation(message: cl.Message):
    MAX_ITER = 50
    CONTEXT = message.content   
    user_proxy  = cl.user_session.get("user_proxy")
    planner     = cl.user_session.get("planner")
    engineer    = cl.user_session.get("engineer")
    critic      = cl.user_session.get("critic")
    executor    = cl.user_session.get("executor")
    scientist   = cl.user_session.get("scientist")
    groupchat   = autogen.GroupChat(agents=[user_proxy, planner, engineer, scientist, executor, critic], 
                                    messages=[], max_round=MAX_ITER)
    manager     = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)
    print("Running conversation")
    await cl.make_async(user_proxy.initiate_chat)( manager, message=CONTEXT, )


主代码到此结束。


结论

这个多代理 LLM 框架通过利用 ChatGPT 的丰富知识和开源工具,展示了在解决工程问题时超越纯人工范式的潜力。这种方法的准确性和效率依赖于 LLM 对固体力学、流体动力学、多物理场理论、材料科学和编码的深刻理解。如果能在大量相关科学文献和编码数据集的基础上对 LLM 进行更专业、更微调的训练,就能获得更准确的结果。调整模型以编写和执行复杂的工程代码和算法至关重要。


可以创建额外的代理来处理特定的子任务,以加强这种方法。例如,一个代理可以生成初始几何体或 CAD 文件,另一个代理可以制作网格,第三个代理可以编写数值算法。这种分工可以减少错误,并最大限度地减少有效解决问题所需的迭代和群聊对话。


此外,这些自主代理可以使用 API 与 SOLIDWORKS、ANSYS、Abaqus 和 LS-DYNA 等商业工程软件进行交互。培训 LLM 为这些 API 编写脚本将有助于顺利进行交互。这种方法可以自动解决工程设计和分析问题,为工程研究和创新中的人机无缝协作铺平道路。

文章来源:https://ai.gopubby.com/autonomous-llm-agents-solving-solid-mechanics-fluid-dynamics-496cedf96073
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消