Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
Elephant RoboticsMavisHuang
Published © GPL3+

AI-Powered Robot Control with a Custom DeepSeek AI Agent

In our project, we enable the AI to learn from provided texts, allowing it to automatically write code and execute tasks to control myCobot.

BeginnerFull instructions provided1 hour575

Things used in this project

Story

Read more

Code

DeepSeek_LearnDocx.py

Python
import os
from docx import Document
from openai import OpenAI
import subprocess
import re

def extract_text_from_word(doc_path):
    """Extract From Word (.docx) """
    doc = Document(doc_path)
    return "\n".join([para.text for para in doc.paragraphs])


def load_local_documents(directory):
    """Read Word 文档"""
    texts = []
    for filename in os.listdir(directory):
        if filename.endswith(".docx"):
            file_path = os.path.join(directory, filename)
            text = extract_text_from_word(file_path)
            texts.append(text)
    return texts

def execute_command(command):
    """Executes a shell command and returns stdout and stderr."""
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        return result.stdout, result.stderr
    except Exception as e:
        return None, str(e)

def run_command():
    """Runs the specific command and prints the output."""
    command = "conda activate base &&  E: && cd E:\MyCode\Agent_Deepseek\RobotData && python generated_script.py"
    #print(f"\nRunning command: {command}")


    stdout, stderr = execute_command(command)

    if stdout:
        print(f"\nOutput:\n{stdout}")
    if stderr:
        print(f"\nError:\n{stderr}")


word_documents = load_local_documents("E:\MyCode\Agent_Deepseek\RobotData")
context = "\n".join(word_documents)  # Merge all text

client = OpenAI(
    api_key="xxxx {Your API}",
    base_url="https://api.deepseek.com"
)

while True:
    # Get user input
    query = input("\n请输入你的指令 (输入 'exit' 退出):")
    if query.lower() == "exit":
        print("退出程序。")
        break

    completion = client.chat.completions.create(
        model="deepseek-chat",
        temperature=0.6,
        messages=[
            {"role": "system", "content": "你是一个六轴协作机器人专家,主要研究协作机械臂Python任务。你了解并熟悉掌握Python语言,能够利用现有的pymycobot机器人API接口,给出一份能够使用的完整Python代码。You are  mainly researching Python tasks for collaborative robotic arms. You are familiar with and proficient in the Python language, and can utilize the 'pymycobot' robotic API interface to provide a complete Python code that can be used."},
            {"role": "user", "content": f"reference text:\n{context}\n\n用户问题:{query},请为我生成一个Python代码文件"}
        ]
    )

    # Extract the generated Python code
    message_content = completion.choices[0].message.content
    code_pattern = r"```python(.*?)```"  # Extract code between ```python ... ```
    matches = re.findall(code_pattern, message_content, re.DOTALL)

    if matches:
        python_code = "\n".join(matches).strip()
    else:
        python_code = message_content.strip()

    # Save the extracted Python code to a file
    file_path = "E:\\MyCode\\Agent_Deepseek\\RobotData\\generated_script.py"
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(python_code)

    print(f" running..... ")

    # Run the generated script
    run_command()

Credits

Elephant Robotics
103 projects • 218 followers
An Innovative Robotics Company.
Contact
MavisHuang
1 project • 0 followers
Contact

Comments

Please log in or sign up to comment.