Программируем с ИИ

Использование и разработка софта (преимущественно на ПЦ)

Moderator: Shaos

User avatar
askfind
Devil
Posts: 887
Joined: 04 Jan 2016 09:15
Location: Russia, S.- Peterburg

Программируем с ИИ

Post by askfind »

AI Cursor попытка совместной работы.

Тренируюсь на проекте эмулятора троичной машины Setun-1958 на языке Си.

Ссылки:
--------------
1) The AI Code Editor. Built to make you extraordinarily productive, Cursor is the best way to code with AI. - https://www.cursor.com

2) Виртуальная машина троичной цифровой машина "Сетунь" также известная как МЦВМ "Сетунь"), написанный на языке программирования C. - https://github.com/askfind/Emulator-Setun-1958.git

3) Обзор AI-ассистента Cursor для разработчиков - https://habr.com/ru/companies/otus/articles/844866/

Компьютер
-------------------
Ноутбук с GNU/OS Linux Ubuntu 20.04.6 LTS .
vendor_id : GenuineIntel
cpu family : 6
model : 42
model name : Intel(R) Core(TM) i7-2630QM CPU @ 2.00GHz

Использование
---------------------------

int Test1_Setun_Reset()
{
int v = 0;

trs_t t = {0};
t.l = 9;
t.t0 = 0xff00;
t.t1 = 0x00ff;

view_short_reg(&t, "t=");

return v;
}

LOG Terminal:
t=: [-00000000], Z0000, (-6561)
[ Stop Setun-1958 ]

Создал тестовую функцию. При помощи TAB система мне подсказывает, на основании кода выше, как инициализировать троичный тип.

Действительно AI подсказывает какие строки ниже ещё добавить.

Работает. Полезный инструмент .

Необходимо почитать как этим грамотно пользоваться.)
You do not have the required permissions to view the files attached to this post.
"Ученье свет, а неученье — тьма. Дело мастера боится, и коль крестьянин не умеет сохою владеть — хлеб не родится." (С)
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: AI Cursor редактор кода с ИИ

Post by Shaos »

Вроде говорят Cursor силён только в питоне и джаваскрипте, а во всех остальных языках - слабоват

Я сам какое-то время уже хочу этот ИИ редактор попробовать т.к. сам в питоне не эксперт (хотя свою первую программу на питоне я написал ещё в 1998 году - в те времена это был ещё питон v1.5)
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программистские редакторы с ИИ

Post by Shaos »

Заменил тему топика на более общую - "Программистские редакторы с ИИ"

Это потому что на работе доевелось поработать с плагином GitHub Copilot в программистском редакторе PyCharm (это JetBrains IDE заточенный под разработку программ на Python) - этот плагин имеет "чат", а также может прямо в коде интеллектуально дополнять по мере написания программы - при этом он может использовать несколько моделей из списка - несколько gpt, несколько claude и даже gemini от гугла есть. Часто этот самый копайлэт очень чотко угадывает что я хочу написать и дополняет прям как надо, но иногда всё-таки тупит :roll:
aviator
Doomed
Posts: 451
Joined: 10 Dec 2008 08:39
Location: Стокгольм, Швеция

Re: Программистские редакторы с ИИ

Post by aviator »

Shaos wrote: 18 Oct 2025 17:47 Это потому что на работе доевелось поработать с плагином GitHub Copilot в программистском редакторе PyCharm (это JetBrains IDE заточенный под разработку программ на Python) ... Часто этот самый копайлэт очень чотко угадывает что я хочу написать и дополняет прям как надо, но иногда всё-таки тупит :roll:
Мне приходится использовать Питон для "одноразового" скриптинга, как вариант продвинутого интерпретатора shell. Тоже пользуюсь PyCharm и этот копилот, как и другие модели, пока ни разу не сообразил, что мне нужно. Постоянно советовал какую-то дичь, и я его отключил.
С уважением, Сергей.
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

В копилоте можно модели переключать - по умолчанию идёт Claude Sonnet 4.5, но можно включить другие от Антропика либо ChatGPT либо Gemini

Попробовал тут на работе Github Copilot CLI - типа для интерфейса командной строки в терминале т.е. никакого редактора ненадо :mrgreen:

И там по умолчанию тоже Claude Sonnet 4.5 и народ пишет типа это же тоже самое, что и Claude Code получается - и я такой думаю дай ка поставлю себе дома этот самый Claude Code да погляжу сам...

https://code.claude.com/docs/en/overview

P.S. А с Github Copilot в частном порядке я не хочу иметь никаких дел :roll:

P.P.S. Поменял название темы ещё раз - пусть будет «Программируем с ИИ» т.к. оказалось, что можно обойтись вообще без редактора :kruto:
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

Установил Claude Code в наипоследнейший дебиан, запущенный через VirtualBox:
VirtualBox_Debian Testing_16_01_2026_09_03_50.png
Залогинился через сервис Claude Console, куда положил $5 на первое время, и оно сначала спросило за тему:
VirtualBox_Debian Testing_16_01_2026_09_04_27.png
Из моделей там только Sonnet (стандартная), Opus (посильнее) и Haiku (побыстрее) - вот результат работы команды /model:
VirtualBox_Debian Testing_16_01_2026_09_14_03.png
Попросил написать хэлловорлд на сях:
VirtualBox_Debian Testing_16_01_2026_09_23_11.png
И это мне стоило почти 5 центов :o
Screenshot from 2026-01-16 09-17-00.png
You do not have the required permissions to view the files attached to this post.
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

Попросил добавить в hello.c печать текущего времени для текущей таймзоны:
Screenshot from 2026-01-16 09-27-09.png
Screenshot from 2026-01-16 09-29-25.png
Как можно видеть это стоило ещё 5 центов с хвостиком, но на сайте оно округлилось до 12 центов:
Screenshot from 2026-01-16 09-38-19.png
А от моих предоплаченных 5 баксов осталось $4.87 (т.е. как будто бы снято 13 центов, а не 12):
Screenshot from 2026-01-16 09-41-40.png
P.S. Вообще я ведь ещё дёрнул вебапи курлом один раз, чтобы проверить, что токен работает - возможно оттуда эти лишние центы и добавились…
You do not have the required permissions to view the files attached to this post.
imsushka
Doomed
Posts: 366
Joined: 01 Jan 2022 04:34
Location: USSR, Tashkent

Re: Программируем с ИИ

Post by imsushka »

пользуюсь дипсик и чатгпт
оба бесплатные

заказываю модели vhdl и на асме для z80
и то и то надо не только напильником но и рубанком доделывать
но плюс ручками партянку писать дольше
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

я дипсик хочу у себя локально запустить

P.S. а вообще дипсику до соннета как до луны (да и чатгпт тоже подотстал)
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

Продолжаю играться с Клодом - во вновь запущенном Claude Code вспомнил сессию с помощью команды /resume и затем с помощью /init создал файл с правилами CLAUDE.md - это сожрало ещё 10 центов :o
VirtualBox_Debian Testing_16_01_2026_21_23_13.png
Переключаюсь на более легковесную модель Хайку:
Screenshot from 2026-01-16 21-26-18.png
You do not have the required permissions to view the files attached to this post.
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

Похоже я научил Клода программировать на своём языке программирования Robby :)
Для начала я подсунул ему файл CLAUDE.md с таким вот описанием языка:

 CLAUDE.md

Code: Select all

# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This is an attempt to teach Claude to use Robby programmin language that is used to build simple applications for retrocomputers even though initially it was used to program simulated robots.

Robby could be understood as oversimplified C - it's also having curly brackets to identify code blocks, using // for comments and operates with familiar coding primitives as if,else,for,contine,break (but not do/until or switch).

All variables are global integers and there is no need to declare variable before use - first use is treated as declaration.

1-letter variable names are reserved for low-level registers (for example A,B,C are used to represent arguments of any function), so it's better name variables with more than 2 characters.

Program files for ROBBY have extension .R or .Robot. If it's a main file in the project then it should have keywords author and robot in the beginning that specify name of the author and name of the program and also main() function that should be 1st function in the file. There is no need to declare function prototype first before calling it - program can call any function even if it's declared afterwards.

To print something on the screen Robby uses keyword say, like say "Hello, World!" and if we need to print content of some variable we should use symbol & like say "Count=&Count " (alsways add space character after variable name to show compiler that name is ended).

Simplest Robby program TEST.R written by Sasha:

```
author "Sasha"
robot "Test"

main()
{
 say "Hello, World!"
}
```

Program that print 10 digits from 0 to 9:

```
author "Sasha"
robot "Count"

main()
{
 for(Count=0;Count<10;Count++)
 {
   say "Count=&Count "
 }
}
```

## Build and Run

Compile the program to Robby Object (with extension .RO):
```bash
robby TEST.R
```

In case of success the output should have word Ok! in it but if any error occured then it will be words ERROR and Sorry in the output.

Run the compiled program is not yet ready.

## Code Structure

- `TEST.R` - Simple program that prints "Hello, World!"


А потом пообщался в чате:

Code: Select all

                                                                                                                 
 ▐▛███▜▌   Claude Code v2.1.11                                                                                   
▝▜█████▛▘  Haiku 4.5 · API Usage Billing                                                                         
  ▘▘ ▝▝    ~/Sources/robby                                                                                       
                                                                                                                 
❯ do you understand programming language Robby now?                                                              
                                                                                                                 
● Yes, I understand the basics of Robby now. From the CLAUDE.md instructions, I've learned:                      
                                                                                                                 
  Key characteristics:                                                                                           
  - Simplified C-like language with curly brackets, // comments                                                  
  - All variables are global integers (no declaration needed)                                                    
  - Supports: if, else, for, continue, break                                                                     
  - 1-letter names reserved for registers; use 2+ letter names for variables                                     
  - Output via say keyword and & for variable values                                                             
                                                                                                                 
  File structure:                                                                                                
  - Extensions: .R or .Robot                                                                                     
  - Main files must have author, robot keywords and main() function first                                        
  - Functions can be called before they're declared                                                              
                                                                                                                 
  Build:                                                                                                         
  robby program.R  # compiles to .RO file                                                                        
                                                                                                                 
  How can I help you with Robby programming?                                                                     
                                                                                                                 
❯ Also it support labels and goto                                                                                
                                                                                                                 
● Got it. Thank you for that clarification. So Robby also supports:                                              
                                                                                                                 
  - Labels: Named points in code that can be jumped to                                                           
  - goto: Statement to jump execution to a labeled location                                                      
                                                                                                                 
  This adds control flow capabilities beyond just if/else and loops. So the language supports both structured    
  control flow (if, else, for, continue, break) as well as direct branching with labels and goto.                
                                                                                                                 
  I'll keep this in mind when working with Robby code. Is there anything specific you'd like help with regarding 
  Robby programming?                                                                                             
                                                                                                                 
❯ /cost                                                                                                          
  ⎿  Total cost:            $0.0162                                                                              
     Total duration (API):  14s                                                                                  
     Total duration (wall): 2m 22s                                                                               
     Total code changes:    0 lines added, 0 lines removed                                                       
     Usage by model:                                                                                             
             claude-haiku:  266 input, 922 output, 34.5k cache read, 6.3k cache write ($0.0162)                  
                                                                                                                 
❯ Can you write a new Robby program that count from 1 to 100 but instead if for loop it uses if/else and         
  goto?                                                                                                          
                                                                                                                 
● I'll create a Robby program that counts from 1 to 100 using labels and goto:                                   
                                                                                                                 
  author "Sasha"                                                                                                 
  robot "CountWithGoto"                                                                                          
                                                                                                                 
  main()                                                                                                         
  {                                                                                                              
   Counter = 0                                                                                                   
                                                                                                                 
   loop:                                                                                                         
   Counter = Counter + 1                                                                                         
   say "Counter=&Counter "                                                                                       
                                                                                                                 
   if(Counter < 100)                                                                                             
   {                                                                                                             
    goto loop                                                                                                    
   }                                                                                                             
   else                                                                                                          
   {                                                                                                             
    say "Done!"                                                                                                  
   }                                                                                                             
  }                                                                                                              
                                                                                                                 
  This program:                                                                                                  
  1. Initializes Counter to 0                                                                                    
  2. Defines a loop: label                                                                                       
  3. Increments the counter and prints it                                                                        
  4. Uses if/else to check if Counter < 100                                                                      
  5. If true, uses goto loop to jump back to the label                                                           
  6. If false (reached 100), prints "Done!" and exits                                                            
                                                                                                                 
  The result is the same counting behavior as a for loop, but implemented with conditional branching and goto    
  statements.                                                                                                    
                                                                                                                 
❯ Can you compile it for me? Remember it's robbyc (Robby Compiler)                                               
                                                                                                                 
● Write(CountWithGoto.R)                                                                                         
  ⎿  Wrote 21 lines to CountWithGoto.R                                                                           
      1 author "Sasha"                                                                                           
      2 robot "CountWithGoto"                                                                                    
      3 main()                                                                                                   
      4 {                                                                                                        
      5  Counter = 0                                                                                             
      6  loop:                                                                                                   
      7  Counter = Counter + 1                                                                                   
      8  say "Counter=&Counter "                                                                                 
     … +11 lines (ctrl+o to expand)                                                                              
                                                                                                                 
● Bash(robbyc CountWithGoto.R)                                                                                   
  ⎿  ROBBYC - Robby Preprocessor & Compiler v2.3.4 (Jan 16 2026)                                                 
     Copyright (c) 1998-2025, Alexander "Shaos" Shabarshin                                                       
     http://nedoPC.org (E-mail: me@shaos.net)                                                                    
     … +7 lines (ctrl+o to expand)                                                                               
                                                                                                                 
● Perfect! The compilation was successful. The program compiled without errors and created CountWithGoto.RO (the 
  compiled Robby Object file).                                                                                   
                                                                                                                 
  The output shows:                                                                                              
  - ROBBYC v2.3.4 preprocessor and compiler ran successfully                                                     
  - Pass 1 and Pass 2 completed                                                                                  
  - Ok! - compilation succeeded                                                                                  
  - CountWithGoto.RO - the output object file                                                                    
                                                                                                                 
  Your program is ready to run!                                                                                  
                                                                                                                 
❯ /cost                                                                                                          
  ⎿  Total cost:            $0.0420                                                                              
     Total duration (API):  38s                                                                                  
     Total duration (wall): 5m 58s                                                                               
     Total code changes:    21 lines added, 0 lines removed                                                      
     Usage by model:                                                                                             
             claude-haiku:  1.9k input, 2.8k output, 160.9k cache read, 8.1k cache write ($0.0420)      
И как можно видеть это всё мне стоило всего 4 цента с моделью Haiku ;)
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

Объяснил чуваку про функции и массивы:

 CLAUDE.md

Code: Select all

# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This is an attempt to teach Claude to use Robby programmin language that is used to build simple applications for retrocomputers even though initially it was used to program simulated robots.

Robby could be understood as oversimplified C - it's also having curly brackets to identify code blocks, using // for comments and operates with familiar coding primitives as if/else,do/while,for,contine,break,goto and labels (but not switch - instead of switch we can use arrays of labels).

Semicolon at the end of the line is optional, but we can use it for separation if we have a few statemepnts in one line.

All variables are global integers (no structures, no unions) and there is no need to declare variable before use - first use is treated as declaration.

1-letter variable names are reserved for low-level registers (for example A,B,C are used to represent arguments of any function), so it's better name variables with more than 2 characters.

Program files for ROBBY have extension .R or .Robot and if it's a main file in the project then it should have keywords author and robot in the beginning that specify name of the author and name of the program and also main() function that should be 1st function in the file. There is no need to declare function prototype first before calling it - program can call any function even if it's declared afterwards.

To print something on the screen Robby uses keyword say, like say "Hello, World!" and if we need to print content of some variable we should use symbol & like say "Count=&Count " (alsways add space character after variable name to show compiler that name is ended).

Simplest Robby program TEST.R written by Sasha:

```
author "Sasha"
robot "Test"

main()
{
 say "Hello, World!"
}
```

Program that print 10 digits from 0 to 9:

```
author "Sasha"
robot "Count"

main()
{
 for(Count=0;Count<10;Count++)
 {
   say "&Count "
 }
}
```
All functions are declared with () even if they have 1 or more arguments - inside of the function we can get access to arguments using registers names A,B and C:
```
author "Sasha"
robot "Functions"

main()
{
 for(Count=0;Count<10;Count++)
 {
   printCount(Count)
 }
}

printCount() // A-Count
{
 say "&A "
}

```
If function wants to return some value it may use return keyword, but it will just set register L and outside of the function we need to use L to get the value (so functions are not yet ready to be used inside of expressions).

Also we may have arrays that must be declared in the beginning of the function main() with keyword def (and they will be visible across all program as globals) - we can declare arrays with or without initialization like:
```
author "Sasha"
robot "Arrays"

main()
{
 def A1[10] // without initialization (expected to be zeros)
 def A2[5] = {1,2,3,4,5} // with initialization
 say "1st element of array A2 is &A2[0] "
 A2[0] = A1[0]
 say "1st element of array A2 is &A2[0] "
}
```

## Build and Run

Compile the program to Robby Object (with extension .RO):
```bash
robbyc TEST.R
```

In case of success the output should have word Ok! in it but if any error occured then it will be words ERROR and Sorry in the output.

Run the compiled program is not yet ready.

## Code Structure

- `TEST.R` - Simple program that prints "Hello, World!"
- `COUNT.R` - Simple program that prints digits from 0 to 9
- `Functions.R` - Simple program that prints digits from 0 to 9 using another function
- `ARRAYS.R` - Simple program that shows how to use arrays

И спросил что напечатает программа ARRAYS.R:

Code: Select all

author "Sasha"
robot "Arrays"

main()
{
 def A1[10] // without initialization (expected to be zeros)
 def A2[5] = {1,2,3,4,5} // with initialization
 say "1st element of array A2 is &A2[0] "
 A2[0] = A1[0]-1
 say "1st element of array A2 is &A2[0] "
}
Ответ Клода:
Screenshot from 2026-01-16 23-26-36.png
И это облегчённая модель Haiku :P
You do not have the required permissions to view the files attached to this post.
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

В несколько итераций наводящих вопросов и кратких объяснений чувак понял как можно имитировать switch и накатал вот такое:

Code: Select all

author "Sasha"
robot "CountWords"

main()
{
 def labels[10] = {label_zero, label_one, label_two, label_three, label_four, label_five, label_six, label_seven, label_eight, label_nine}
 for(Count=0;Count<10;Count++)
 {
   printWord(Count)
 }
}

printWord() // A-Count
{
 goto labels[A]

 do
 {
  label_zero: say "zero"; break
  label_one: say "one"; break
  label_two: say "two"; break
  label_three: say "three"; break
  label_four: say "four"; break
  label_five: say "five"; break
  label_six: say "six"; break
  label_seven: say "seven"; break
  label_eight: say "eight"; break
  label_nine: say "nine"; break
 }while(0)
}
Умён чертяка :roll:

P.S. В итоге на всё это обучение модели Haiku новому языку я потратил 60 центов :roll:
You do not have the required permissions to view the files attached to this post.
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

60 центов за 6 минут работы API означает, что "программист" Claude Haiku стоит 6 долларов в час, что в-принципе достаточно дёшево :roll:

Стандартный "программист" Claude Sonnet за то же самое взял бы $18/час, а "программист" Claude Opus (самый сильный) - $30/час :o
User avatar
Shaos
Admin
Posts: 24873
Joined: 08 Jan 2003 23:22
Location: Silicon Valley

Re: Программируем с ИИ

Post by Shaos »

Клоду также можно давать простые задания типа "преобразуй все GIF-файлы в этом директории в формат PNG" - в результате модель Haiku сгенерировала bash-запросы, которые переконвертировали мне тыщу с лишним файлов за 27 центов :roll: