Интеграция сайта с DeepSeek AI по API

Введение 

Deepseek - китайская нейросеть, работающая в текстовом формате, с большими возможностями с недорогим API.

Как работать с DeepSeek API 

Регистрируемся на сайте Deepseek.com (поддержка китайского и английского языков). 

В кабинете получаем токен API. На старте дается от 5 до 20 млн бесплатных токенов.

Оплата API производится через карту не российского банка. 

Заносим в /settings с кодом dsToken полученный токен доступа. 

Далее приводим интеграцию DeepSeek как часть пакета aichat, где подключение ds1 играет роль провайдера доступа к Deepseek для ИИ профиля.

Создаем в /asapi метод API ds1. 

Процедура request 

CREATE PROCEDURE [dbo].[api_ds1_request]
  @parameters ExtendedDictionaryParameter READONLY,  -- (Key, Value2)
  @username nvarchar(32)  -- current site user
AS
BEGIN
 declare @text nvarchar(max) = (select value2 from @parameters where [key]='text')
    declare @systemPrompt nvarchar(max) = (select value2 from @parameters where [key]='systemPrompt')
    declare @profile nvarchar(max) = (select value2 from @parameters where [key]='profile')
    declare @url nvarchar(max) = 'https://api.deepseek.com/chat/completions'
    declare @token nvarchar(max) = dbo.as_setting('dsToken', '')
	
    declare @g uniqueidentifier = (select try_convert(uniqueidentifier, value2) from @parameters where [key]='g')
   declare @profileID int = (select id from as_apiProfiles where code = @profile)

 	declare @commands nvarchar(max) = ''
    select @commands = @commands + isnull(prompt, '') + char(10) from as_apiProfileCommands 
    where profileID = @profileID and len(prompt)>3 and isActive = 1
    

	if(len(@commands)>4) begin 
    	set @systemPrompt = @commands + ' В остальных случаях не используй JSON с полем type. ' + @systemPrompt
    end     
    
    
	declare @json nvarchar(max) = (
      select 'deepseek-chat' model,
	
		0.7 temperature,
      	(
          select role, content from (
   			/*
            это если нужно историю запросов зацепить для чата
            select top 10 'user' role, request content, created dt from as_apiProfileLog
            where profileID = @profileID  and g <>@g order by id desc
            union
            select top 10 'assistant' role, response content, dateadd(second, 5, created) dt from as_apiProfileLog
            where profileID = @profileID  and g <>@g and len(request)>0
            order by id desc
            union
            */
          select 'system' role,  isnull(@systemPrompt, '') content, dateadd(ms, -200, getdate()) dt  where len(@systemPrompt)>4
          union
          select 'user' role,  	isnull(@text, '') content, getdate() dt ) t1
          order by dt
          FOR JSON PATH)  messages
	  for JSON PATH,WITHOUT_ARRAY_WRAPPER
    )

  -- SELECT 1  Msg, Result, Url (outer request url)
  select '' Msg, 1 Result, @url Url, '' ContentType,   '' Certpath, '' CertPass, '' RequestParameterForResponse, 0 Timeout

  -- SELECT 2 PARAMETERS - request parameters
  select 'Authorization' name, 'Bearer ' + @token value, 'header' [type]  
  union
  select 'json' name, @json value, 'json' [type]


END

Процедура response

CREATE PROCEDURE [dbo].[api_ds1_response]
  @response nvarchar(max),
  @parameters ExtendedDictionaryParameter READONLY,  
  @username nvarchar(32)
AS
BEGIN
	declare @g uniqueidentifier = (select try_convert(uniqueidentifier, value2) from @parameters where [key]='g')

  	declare @resp nvarchar(max) = @response
    declare @tokens int = 0
	if(ISJSON(@response) =1) begin
    	declare @t table (content nvarchar(max))
		insert into @t
        SELECT content FROM OPENJSON(@response, '$.choices')
        WITH (
			content NVARCHAR(MAX) '$.message.content'			
		)
		declare @messages nvarchar(max)  = ''
		select @messages = @messages + isnull(content, '') + char(10)+ char(10) from @t
		select @resp =  @messages

        set @tokens = JSON_VALUE(@response, '$.usage.total_tokens')

        declare @msg nvarchar(max) = ''

        -- обработка команды, если она есть в JSON
        exec ai_processCommand
        	@s = @resp,
            @ai = 'deepseek',
            @username = @username,
            @parameters = @parameters,
            @msg = @msg OUTPUT

        if(len(@msg)>0) set @resp = @resp + char(10)+ '
---
## Система:
'+ @msg
    end

    update as_apiProfileLog
    set response = @resp,
    	jsonResponse = @response,
        tokens = @tokens
    where g = @g
END
Страница-источник на сайте falconspace.ru