Alice PRO – for mobile developers

Hello everyone! My name is Sergey, my main focus is mobile applications, but in addition to that I closely monitor what is happening with AI.

Recently we all saw the news:

On April 10, Yandex introduced the “New Generation Alice” and a pro subscription, which includes advanced features.

Without hesitation, I immediately subscribed and decided to try what it was.

In my work, I often use the ChatGPT service, but it is not always convenient, especially because of the need to enable a VPN. Let's try to answer the question: can a developer of mobile applications, for example on the iOS platform, use Yandex GPT in his daily work?

A small digression. As I understand it, this year all companies around the world are urgently looking for ways to monetize AI services, since everyone understands that this is “cool”, but it is not yet clear where the money is =)

So, let's go to https://a.ya.ru

Help with code

Let's imagine that we are mobile developers who write in Swift every day. We want to use YaGPT every day in our work. To do this, we will test its competence against GPT 4o from OpenAI.

Our interview for the role of AI assistant will take place in three stages:

  1. Algorithmic session. Let's give some problems with leetcode.

  2. Code fixWe'll give you a small piece of code and ask you to improve it.

  3. Theoretical questions. Let's try to ask a few theoretical questions.

Let's take the first problem with the “easy” level using leetcode

leetcode

leetcode

We translate the text of the task into Russian, to be fair, we are still working with YaGPT

Prompt text

Task
Given an array of integers nums and an integer target, return the indices of the two numbers such that their sum equals target.
You can assume that each input has exactly one solution, and you cannot use the same element twice.
You can return the response in any order.

Example 1:

Input: nums = [2,7,11,15]target = 9
Conclusion: [0,1]
Explanation: Since nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4]target = 6
Conclusion: [1,2]
Example 3:

Input: nums = [3,3]target = 6
Conclusion: [0,1]

Restrictions:
2 <= array length nums <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
There is only one correct answer.

Start code

class Solution {
func twoSum(_ nums: [Int]_ target: Int) -> [Int] {}

}

We get results

YaGPT

Checking the answer in leetcode

Now let's compare it with ChatGPT 4o's solution

GPT 4o's response was more optimized, but overall both networks handled the solution.

Let's take one more problem to check

Prompt text

An integer x is given. Return true if x is a palindrome, false otherwise. An integer is a palindrome when it reads the same from left to right as from right to left. For example, 121 is a palindrome, while 123 is not a palindrome.

Example 1: Input: x = 121 Output: true

Explanation: 121 is read the same from left to right and from right to left.

Example 2: Input: x = -121 Output: false

Explanation: From left to right it reads -121. From right to left it becomes 121-. Therefore it is not a palindrome.

Example 3: Input: x = 10 Output: false

Explanation: From right to left it reads as 01, so it is not a palindrome.

Constraints: -2^31 <= x <= 2^31 - 1

Initial code class Solution { func isPalindrome(_ x: Int) -> Bool { } }

Let's try

We try to send the code for verification and see an error unfortunately =(

We check the code that GPT 4o returns. The results speak for themselves

Code correction

We'll give you a small piece of code and ask you to improve it.

Note

Initially, I didn't know that YaGPT has a character limit. When I started testing it, I thought that I could change the task to a simpler one. But the layout task is very basic, and AI can really help with that. So I decided not to change the task and leave it as is.

Let's assume you have a screen like this in your app.

And then they come to you and say, “Oh, we need to replace the text.” You say, “Of course, it’s a two-minute task.” And you replace the text and see the following.

The screen moved, no one expected that there would be so much text there. There is no scrolling, of course. What should be done? That's right, we need to add a scroll to this screen so that all elements can be scrolled, but let's leave the “Share” button fixed outside the scroll. So, let's try to send this problem to Alice and to GPT.

Prompt text
import UIKit
import SnapKit

class ViewController: UIViewController {
    
    let headerBlockView: UIView = {
        let view = UIView()
        view.backgroundColor = .lightGray
        return view
    }()
    
    let linkContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .lightGray
        view.layer.cornerRadius = 10
        return view
    }()
    
    let referralLinkLabel: UILabel = {
        let label = UILabel()
        label.text = "https://google.com"
        label.textColor = .systemBlue
        label.numberOfLines = 1
        label.textAlignment = .center
        return label
    }()
    
    let copyButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Copy", for: .normal)
        button.addTarget(self, action: #selector(copyLink), for: .touchUpInside)
        return button
    }()
    
    let shareButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Поделиться", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .red
        button.layer.cornerRadius = 10
        button.addTarget(self, action: #selector(shareLink), for: .touchUpInside)
        return button
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.text = """
        Искусственный интеллект (ИИ) о потенциал уже сейчас меняет мир, открывая новые возможности во всех сферах нашей жизни. ИИ способен анализировать огромные объемы данных за считанные секунды, находя в них закономерности и выводы, которые были бы недоступны человеку. Это приводит к улучшению решений в медицине, финансах, производстве и других областях.
        """
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 14)
        return label
    }()
    
    let agreementLabel: UILabel = {
        let label = UILabel()
        label.text = """
        Нажимая "Поделиться", ты соглашаешься с правилами программы.
        """
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = .gray
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        setupUI()
    }
    
    func setupUI() {
        view.addSubview(headerBlockView)
        view.addSubview(linkContainerView)
        linkContainerView.addSubview(referralLinkLabel)
        linkContainerView.addSubview(copyButton)
        view.addSubview(descriptionLabel)
        view.addSubview(shareButton)
        view.addSubview(agreementLabel)
        
        headerBlockView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(200)
        }
        
        linkContainerView.snp.makeConstraints { make in
            make.top.equalTo(headerBlockView.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(50)
        }
        
        referralLinkLabel.snp.makeConstraints { make in
            make.centerY.equalTo(linkContainerView.snp.centerY)
            make.leading.equalTo(linkContainerView.snp.leading).offset(16)
        }
        
        copyButton.snp.makeConstraints { make in
            make.centerY.equalTo(linkContainerView.snp.centerY)
            make.leading.equalTo(referralLinkLabel.snp.trailing).offset(8)
            make.trailing.equalTo(linkContainerView.snp.trailing).inset(16)
        }
        
        descriptionLabel.snp.makeConstraints { make in
            make.top.equalTo(linkContainerView.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        shareButton.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-16)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(50)
        }
        
        agreementLabel.snp.makeConstraints { make in
            make.bottom.equalTo(shareButton.snp.top).offset(-8)
            make.leading.trailing.equalToSuperview().inset(16)
        }
    }
    
    @objc func copyLink() {
        UIPasteboard.general.string = referralLinkLabel.text
        let alert = UIAlertController(title: "Copied", message: "Referral link copied to clipboard.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    @objc func shareLink() {
        let activityVC = UIActivityViewController(activityItems: [referralLinkLabel.text ?? ""], applicationActivities: nil)
        present(activityVC, animated: true, completion: nil)
    }
}


Положи все объекты на скрол вью, чтобы все элементы скролились так как в label может быть много текста
Кнопка поделится должна быть над scollview чтобы она не скролилась

What we got with GPT 4o

We try to use YaGPT, and unfortunately we see a limitation on the entered text, and the entire screen does not fit in the answer (even half)

Never mind, I thought. Let's try to enter Yandex Cloud, maybe there is no such input limitation there. But no, unfortunately we see the same limitation.

As a result, in this test we give YaGPT a minus.

Theoretical question

Let's try to ask a basic question about working with memory in swift AI

Question

Tell me how to work with memory in swift

YaGPT

В Swift управление памятью осуществляется через два основных механизма: 
Automatic Reference Counting (ARC) и Manual Memory Management.Automatic Reference Counting (ARC)ARC является предпочтительным 
и дефолтным механизмом управления памятью в Swift.
Он автоматизирует процесс выделения и освобождения памяти, упрощая работу 
разработчика. 

ARC отслеживает количество сильных ссылок на объекты и освобождает память,
когда количество ссылок становится равным нулю.Manual Memory ManagementНесмотря на то, 
что ARC является основным механизмом управления памятью в Swift, иногда требуется более точный контроль над выделением и освобождением памяти.
Для этого используются технологии вроде UnsafeMutablePointer и UnsafeBufferPointer, 
которые позволяют напрямую управлять памятью.

Пример работы с памятью в SwiftРассмотрим пример использования
ARC:class 

University {
 var title: String
 init(title: String) {
 self.title = title
 print("\(title) has been initialized.")
 }
 deinit {
 print("\(title) has been deallocated.")
 }
}

func assignTitle() {
 _ = University(title: "Cambridge")
}

assignTitle()

В этом примере создается класс University с одним свойством title типа String. При создании экземпляра класса University с помощью метода init печатается сообщение о инициализации объекта. После того как экземпляр выходит из области видимости, вызывается метод deinit, который печатает сообщение о деинициализации объекта.Этот пример демонстрирует, как ARC автоматически управляет памятью, освобождая ее после того, как экземпляр класса University выходит из области видимости.

GPT 4o

Работа с памятью в Swift в основном управляется автоматически с помощью механизма ARC (Automatic Reference Counting). Однако, чтобы эффективно использовать память и избегать проблем, таких как утечки памяти и циклические ссылки, важно понимать, как ARC работает и как управлять ссылками на объекты. Вот подробное руководство по работе с памятью в Swift:

### Основные концепции ARC

#### Сильные ссылки (Strong References)

По умолчанию все ссылки на объекты являются сильными. Это означает, что объект будет удерживаться в памяти до тех пор, пока на него существует хотя бы одна сильная ссылка.

```swift
class Person {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}

var john: Person? = Person(name: "John") // Сильная ссылка на объект Person
```

#### Слабые ссылки (Weak References)

Слабые ссылки не удерживают объект в памяти. Они используются, чтобы избежать циклических ссылок. Слабые ссылки объявляются с помощью ключевого слова `weak`.

```swift
class Apartment {
    weak var tenant: Person?
}

class Person {
    var name: String
    var apartment: Apartment?
    
    init(name: String) {
        self.name = name
    }
}

var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment()

john?.apartment = unit4A
unit4A?.tenant = john

john = nil // Объект Person освобождается, так как единственная сильная ссылка на него установлена в nil
```

#### Несоблюдающие ссылки (Unowned References)

Несоблюдающие ссылки (`unowned`) также не удерживают объект в памяти, но в отличие от слабых ссылок они предполагают, что объект всегда будет существовать при обращении к нему. Несоблюдающие ссылки используются, когда обе стороны взаимосвязи всегда существуют одновременно.

```swift
class Customer {
    var creditCard: CreditCard?
    
    init() {
        self.creditCard = CreditCard(customer: self)
    }
}

class CreditCard {
    unowned let customer: Customer
    
    init(customer: Customer) {
        self.customer = customer
    }
}

var customer = Customer()
// customer имеет сильную ссылку на creditCard, а creditCard имеет несоблюдающую ссылку на customer
```

### Избегание циклических ссылок

Циклические ссылки возникают, когда два объекта удерживают друг друга, создавая цикл. Это приводит к утечкам памяти, так как ARC не может освободить такие объекты. Использование слабых и несоблюдающих ссылок помогает избежать циклических ссылок.

#### Пример циклической ссылки

```swift
class Person {
    var name: String
    var apartment: Apartment?
    
    init(name: String) {
        self.name = name
    }
}

class Apartment {
    var tenant: Person?
}

var john: Person? = Person(name: "John")
var unit4A: Apartment? = Apartment()

john?.apartment = unit4A
unit4A?.tenant = john

john = nil // john и unit4A не освобождаются из памяти из-за циклической ссылки
```

#### Исправление циклической ссылки с использованием слабых ссылок

```swift
class Apartment {
    weak var tenant: Person?
}

// Остальная часть кода остается без изменений
```

### Управление памятью с помощью замыканий (Closures)

Замыкания в Swift захватывают ссылки на любые переменные и объекты, которые они используют внутри себя. Это может привести к циклическим ссылкам, если замыкание и захваченные объекты ссылаются друг на друга.

#### Пример замыкания, создающего циклическую ссылку

```swift
class HTMLElement {
    let name: String
    let text: String?
    
    lazy var asHTML: () -> String = {
        if let text = self.text {
            return "<\(self.name)>\(text)</\(self.name)>"
        } else {
            return "<\(self.name) />"
        }
    }
    
    init(name: String, text: String? = nil) {
        self.name = name
        self.text = text
    }
    
    deinit {
        print("\(name) is being deinitialized")
    }
}

var heading: HTMLElement? = HTMLElement(name: "h1", text: "Hello, world!")
print(heading!.asHTML())
heading = nil // HTMLElement не освобождается из памяти
```

#### Использование захватывающих списков (Capture Lists) для предотвращения циклических ссылок

```swift
lazy var asHTML: () -> String = { [weak self] in
    guard let self = self else { return "" }
    if let text = self.text {
        return "<\(self.name)>\(text)</\(self.name)>"
    } else {
        return "<\(self.name) />"
    }
}
```

### Вывод

Работа с памятью в Swift с помощью ARC позволяет автоматизировать управление памятью и уменьшить количество ошибок, связанных с ручным управлением памятью. Однако важно понимать, как работают сильные, слабые и несоблюдающие ссылки, чтобы эффективно предотвращать утечки памяти и избегать циклических ссылок.

Draw your own conclusions =)

Summary

It’s very cool that we are creating products such as YandexGPT and Gigachat. They are definitely moving in the right direction. But, unfortunately, they are not yet suitable as tools for developers that can be used now.

Do you use AI in your work?

If you are interested in learning more about AI, follow me telegram channel.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *