LangChain  OpenSCAD:   AI-
 


       AI?    :

LangChain (   ,   LLM   );

OpenSCAD (  3D?      ).

 :

    LangChain  OpenSCAD;

 ,      3D?;

 :    ?   OpenSCAD ?   ;

  ,    .

 :

     3D?;

      ;

  (, )  3D.

  :

 AI?;

  ,  AI  ;

,  NLP  3D?.

:    ,     3D?.







LangChain  OpenSCAD:   AI-





 1.   LangChain  OpenSCAD




  LangChain  OpenSCAD     AI?,           LangChain   ? OpenSCAD          ;       LangChain,    ?,    OpenSCAD     ,      ,     ,    ,    ,        OpenSCAD    STL?     3?D?;   ,  LangChain       (chains),      LLM,  ,  API    ,      ,     (prompt, model, memory, tool, output parser)           ;  OpenSCAD       ,     ,         :  LLM  OpenSCAD (  )   OpenSCAD  LLM (    ,      );            `Tool`?,    LangChain,        `openscad`  ,     (,  G?code   `.scad`)       ,   `output parser`     Beschreibung    ,     ;             ,     3?D?,           ,   CAD?,      ;       (chain) LangChain,       prompts?,   ?  LLM,     `LLMChain`,         (, , , ),        `OpenSCADExecutorTool`,     `.scad`       OpenSCAD  `subprocess`   ;      `STLExportStep`   ,   OpenSCAD   headless (`openscad -o output.stl model.scad`)      STL?,     ,            ;         (`memory`),       ,      ,           ;        Python    : `langchain`, `langchain_community` (  ), `openai`     LLM?API,   `subprocess`, `os`, `tempfile`  `re`        ;      :



`from langchain.agents import Tool, AgentType`

`from langchain.llms import OpenAI`

`from langchain.chains import LLMChain`

`from langchain.prompts import PromptTemplate`

`import subprocess, tempfile, os, re`

`llm = OpenAI(model="gpt-4-turbo", temperature=0.2)`

`scad_prompt = PromptTemplate(input_variables=["spec"], template="Generate a complete OpenSCAD script based on the following specification: {spec}")`

`spec_chain = LLMChain(llm=llm, prompt=scad_prompt)`

`def run_scad(script):`

` with tempfile.NamedTemporaryFile(mode='w', suffix='.scad', delete=False) as f:`

` f.write(script)`

` script_path = f.name`

` stl_path = script_path.replace('.scad', '.stl')`

` subprocess.run(['openscad', '-o', stl_path, script_path], check=True)`

` return stl_path`

`scad_tool = Tool(name="OpenSCADExecutor", func=run_scad, description="Executes an OpenSCAD script and returns the path to the generated STL file.")`

`agent = AgentType.create(agent_name="OpenSCADAgent", tools=[scad_tool])`



 `AgentType.create`   ,      ;     `initialize_agent`  `AgentExecutor`     ;  ,  `AgentExecutor`   prompt?, memory  ,       ;     `execute`  ,      `OpenSCADExecutor`,       STL?        ,    ;      :



`def ask_user(request_text):`

` # 1.    LLM`

` spec = spec_chain.run(request_text)`

` # 2.    OpenSCADExecutorTool`

` stl_path = scad_tool.run(spec)`

` # 3.    `

` return stl_path`



          ?, ?      ,  `AgentExecutor`,   ,  ,    OpenSCAD    STL?;        `output parser`,      STL  URL,       ;     `memory` (, `ConversationTokenMemory`),        ,      ,          ;        `"   1.5 "`  `"   5   "`,    ,       ,     ,            ;         (,  ,     )     : `ExtrudeTool`, `RotateTool`, `LoopTool`,                 ;   `Agent`   ,       ,    ,             OpenSCAD;        :       STL?,       OpenSCAD (`<mcad>`, `<cga>`  .)    CI/CD ,         ,             ;        LangChain  OpenSCAD ,   LLM?          ,       CAD?   ,             ;        LLM   GPT?3.5?Turbo   ,     ,   chain?of?thought      ,     ,     ,      OpenSCAD,  ,            ;  ,    LangChain  OpenSCAD     ,    AI?,    ,        OpenSCAD,  ,  STL      3?D?,      LangChain, ,    ,    , ?          .






 2.   AI?




   AI?  OpenSCAD  LangChain



OpenSCAD ?      ,       3D?.  API OpenSCAD     ,      ,            .      LangChain,     AI?,      OpenSCAD,   ,      .



  aking       ,     LangChain,    ?  ,       .



1. 



     .  Python?        langchain?core, langchain?openai (   LLM?),    python?openSCAD,        OpenSCAD   Python.  ,    LLM?, , GPT?4  .



   :

```

python -m venv venv

source venv/bin/activate # Linux/macOS

venv\Scripts\activate # Windows

pip install langchain-core langchain-openai python-openSCAD

```

         LLM: OPENAI_API_KEY   ,    .



2.  



AI?   LangChain    (pipeline) of LLM?,    .  OpenSCAD?    :



?     ,    (, ??es     5  15    estivesse).

?   (prompt template)      ,  LLM.

? LLM?       OpenSCAD.

? ?    :  ,  ,   ,   OpenSCAD.

?       OpenSCAD    .



LangChain       : PromptTemplate, LLMChain, SequentialChain  .         LLMChain     (output parser),      ,    .



3.  



      :    ,  ,   ,      .  :



```

    OpenSCAD.     OpenSCAD,   :

{user_request}

   main()     render()!\n:

```



 {user_request}      .   ,      ,    .



4. LLMChain



  LLMChain   ,   .  :



```

from langchain import LLMChain

from langchain.prompts import PromptTemplate

from langchain_openai import ChatOpenAI



llm = ChatOpenAI(model="gpt-4", temperature=0.2, max_tokens=1500)



prompt = PromptTemplate(

input_variables=["user_request"],

template=(

"    OpenSCAD.     OpenSCAD, "

" :\n{user_request}\n"

"   main()     render()!\n"

":"

)

)



chain = LLMChain(

llm=llm,

prompt=prompt,

output_parser=OpenSCADParser()

)

```



   `OpenSCADParser`   ,        .     .



5.   OpenSCAD



  LLM     ,      .    ,  , :



?        `module`  `//=== START CODE ===//`.

?     .

?     `module main()`  `render()`;    .

?      .



   :



```

import re



class OpenSCADParser:

def parse(self, text: str) -> str:

#       

match = re.search(r"(?s)(module\s+\w+\|?\s*\(.*?\)|//=== START CODE ===//)", text)

if not match:

raise ValueError("    ")

start_idx = match.start(1) if match.lastgroup == "module" else match.start("START CODE")

code = text[start_idx:].strip()

#     

lines = code.splitlines()

processed = []

for line in lines:

if "#" in line:

line = line[: line.index("#")].rstrip()

processed.append(line)

code = "\n".join(processed)

# ,    main  render

if "module main()" not in code:

code += "\nmodule main() {\n}"

if "render()" not in code:

code += "\nrender()\n}"

#     

code = re.sub(r"\n{3,}", "\n\n", code).strip()

return code

```



   ,       ,     OpenSCAD   `openscad -c`        .



6.  OpenSCAD



        OpenSCAD      Python?.     (,  STL),    `execute_openSCAD(code: str) -> str`, :



1.      `temp.scad`.

2.  OpenSCAD    : `openscad -c temp.scad -o temp.stl`.

3.     STL?  ,    2D?.



 :



```

import os

import tempfile

import subprocess



def execute_openSCAD(code: str) -> str:

#   

with tempfile.NamedTemporaryFile(mode="w", suffix=".scad", delete=False) as f:

f.write(code)

temp_path = f.name

try:

#     OpenSCAD

openscad_path = "openscad" #,     PATH

#     STL

cmd = [openscad_path, "-c", temp_path, "-o", temp_path.replace(".scad", ".stl")]

subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

#    STL

stl_path = temp_path.replace(".scad", ".stl")

return stl_path

finally:

#   

os.remove(temp_path)

```



      ,       .



7.    



   ,        ,      . LangChain       LLM.      `Retryable`  ,             : {error_message}   .



   :



```

def handle_error(error_msg: str) -> str:

return f" : {error_msg}.   ,   ."



#  LLMChain  :

chain_with_retry = LLMChain(

llm=llm,

prompt=prompt,

output_parser=OpenSCADParser(),

verbose=True,

callbacks=[handle_error] #  

)

```



 ,    ?,    .



8.  



,        30 , 12 ,  5 .   ,       .    :



```

user_request = "     50 ,  30    20 ,        10 "

result = chain.run(user_request)

parsed_code = OpenSCADParser().parse(result)

stl_file = execute_openSCAD(parsed_code)

print(f" STL   {stl_file}")

```



    STL?,       3D?    3D?.



9. 



       :



?  :    ?,     .




  .


   .

   ,     (https://www.litres.ru/pages/biblio_book/?art=73084763)  .

      Visa, MasterCard, Maestro,    ,   ,     ,  PayPal, WebMoney, ., QIWI ,       .


