We attach AI paws in 1c

I think many have already had enough time to talk to large language models, commonly called artificial intelligence. Entertainment settings, installed by default in almost all currently available to ordinary users “chat rooms” with AI, are really quite entertaining.

But difficult users, those who can string two lines of code together, want something more. It would be nice to turn a nice but generally useless chatterbox into an effective doer. And this can be done, including in the 1C environment, and without straining too much

What we have. First, models. To simplify greatly, to train a large language model, you need, in particular, to prepare many pairs: question – correct answer. And where could you get this? That's right, from Stack Overflow, which at that time did not suspect anything. It was all there in a ready-made form. Large language models can do many things, but they are best at programming, SQL queries, JSON.

Secondly, we have an API. Almost all players now provide access to their models via API. By the way, it is almost unified. That is, everyone is ripping off the pioneer, Open AI. Not everyone, however, manages to resist and not make some changes of their own.

In principle, this would be enough. We write a number of functions (any). Having received a request from the user in natural language, we add signatures of our functions to this request and ask the AI ​​to figure out: which function and with what parameters should be applied. We ask to present the result in JSON. Having JSON in hand, it is easy for us to run the desired function with the desired parameters. This worked, but with some technical misunderstandings (from time to time, the JSON was not quite what was expected, or all sorts of unnecessary blah-blah-blah came in with the JSON, which had to be gotten rid of). Therefore, recently we have, thirdly, a mechanism for receiving function calls. The leaders have it: Google, OpenAI, Anthropic. The Chinese, who are not lagging behind the leaders, have it. Unfortunately, Yandex does not. Sber has it, but their model is in a fundamentally different weight class and does not reach Yandex, not to mention the leaders.

The function call mechanism makes life much easier for developers. But that's not the limit! To improve the life of 1C developers, we have, fourthly, Artificial Intelligence Library for 1C (freely available)

In order to enable function calling, you need to pass an array of references to the “Generate” method.

/Основная функция. Используется технология GPT для генерации текста
//Результат - текст ответа большой языковой модели (LLM) или массив вызовов функций или неопределено в случае ошибки 
//промт - текст запроса пользователя
//модель - ссылка на элемент справочника БИИ_Модели
//температура - число, уровень "креативности" ответа, 0-минимум креативности
//инструменты - необязательный, массив ссылок на справочник БИИ_Инструменты
Функция Генерация(промт, модель, температура, инструменты=неопределено) экспорт

The directory can be accessed from the processing that is included in the extension.

As an example, let's create a description of the GetGoodsBalance function

In addition to the function name, you need to fill in the description and the list of parameters. In the list of parameters, each parameter also has a description. Descriptions should be filled in as clearly as possible. It is the descriptions that the AI ​​will use to decide which function to use.

Let's add one more function definition.

Now let's write the functions themselves (for typical UT/ERP/KA). The function for obtaining the balance of goods will be very simple.

Функция GetGoodsBalance(параметры)
	ЧтениеJSON = Новый ЧтениеJSON;
	ЧтениеJSON.УстановитьСтроку(параметры);	
	данные = ПрочитатьJSON(ЧтениеJSON);
	ЧтениеJSON.Закрыть();
	запрос = новый запрос;
	запрос.Текст =
	"ВЫБРАТЬ
	|	ТоварыНаСкладахОстатки.ВНаличииОстаток КАК ВНаличииОстаток
	|ИЗ
	|	РегистрНакопления.ТоварыНаСкладах.Остатки(, Номенклатура.Наименование ПОДОБНО &Товар) КАК ТоварыНаСкладахОстатки";
	запрос.УстановитьПараметр("Товар","%"+данные.GoodsName+"%");
	выб = запрос.Выполнить().Выбрать();
	если выб.Следующий() тогда
		возврат строка(выб.ВНаличииОстаток);
	иначе
		возврат "Не найден товар: "+данные.GoodsName;
	конецесли;	
КонецФункции

The function of obtaining the balance of mutual settlements is a little more “curly”

Функция GetMutalSettlementsBalance(параметры)
	ЧтениеJSON = Новый ЧтениеJSON;
	ЧтениеJSON.УстановитьСтроку(параметры);	
	данные = ПрочитатьJSON(ЧтениеJSON);
	ЧтениеJSON.Закрыть();
	баланс = 0;

	запрос = новый запрос;
	запрос.Текст =
	"ВЫБРАТЬ
	|	ЕСТЬNULL(РасчетыСКлиентамиОстатки.СуммаОстаток, 0) КАК СуммаОстаток
	|ИЗ
	|	РегистрНакопления.РасчетыСКлиентами.Остатки(, АналитикаУчетаПоПартнерам.Контрагент.Наименование ПОДОБНО &Контрагент) КАК РасчетыСКлиентамиОстатки";
	запрос.УстановитьПараметр("Контрагент","%"+данные.Partner+"%");
	выб = запрос.Выполнить().Выбрать();
	если выб.Следующий() тогда
		баланс=выб.СуммаОстаток;
	конецесли;	

	запрос = новый запрос;
	запрос.Текст =
	"ВЫБРАТЬ
	|	ЕСТЬNULL(РасчетыСПоставщикамиОстатки.СуммаОстаток, 0) КАК СуммаОстаток
	|ИЗ
	|	РегистрНакопления.РасчетыСПоставщиками.Остатки(, АналитикаУчетаПоПартнерам.Контрагент.Наименование ПОДОБНО &Контрагент) КАК РасчетыСПоставщикамиОстатки";
	запрос.УстановитьПараметр("Контрагент","%"+данные.Partner+"%");
	выб = запрос.Выполнить().Выбрать();
	если выб.Следующий() тогда
		баланс=баланс+выб.СуммаОстаток;
	конецесли;	
    возврат баланс;
КонецФункции

We receive from the AI ​​an array of JSON structures, each of which contains the name of the function and a list of parameters with the names of the parameters and their values. All that remains is to make a launcher so that the functions are launched for execution.

Процедура Вызов(имя,параметры)
	если имя="GetGoodsBalance" тогда
		Ответ = Ответ + GetGoodsBalance(параметры)+символы.ПС;
	иначеесли имя="GetMutalSettlementsBalance" тогда
		Ответ = Ответ + GetMutalSettlementsBalance(параметры)+символы.ПС;
	конецесли;	
КонецПроцедуры

We'll check the work. We'll ask for the rest of the goods.

The same answer will be given to all possible forms of the question: “how much tea is in stock”, “tea in stock”, “how much tea do we have”, “leftover tea”, etc.

Let's ask a question about mutual settlements.

As you can see, it works. But there is one problem. Let's turn off the function of receiving the balance of mutual settlements.

And now in response to the request we will receive…

They say that disadvantages are nothing more than a continuation of advantages. And so it is! We have a very good worker. He will never throw up his hands and say: “I can't”. He does not have such an option. He will search and find the most suitable options for action. As we have already seen, if nothing is done, this can lead to undesirable consequences.

Fortunately, the problem is solved in a surprisingly simple way. We just give our worker instructions on what to do when he doesn't know what to do.

Функция need_help(параметры)
	ЧтениеJSON = Новый ЧтениеJSON;
	ЧтениеJSON.УстановитьСтроку(параметры);	
	данные = ПрочитатьJSON(ЧтениеJSON);
	ЧтениеJSON.Закрыть();
	возврат "Не удалось подобрать функцию для вопроса:"+символы.ПС+данные.UserRequest;
КонецФункции

No more confusion now

The function call mechanism is one of the key moments in the practical use of large language models. I hope that this short educational program will help you quickly navigate this issue.

Similar Posts

Leave a Reply

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