Página 1 de 1

API Deepseek

Enviado: 29 Jan 2025 16:20
por JoséQuintas
Apenas repassando.
Foi postado no harbour-users no dia 03/janeiro/2025, por Antonio Linares - fivewin.

Código: Selecionar todos

#include "c:\harbour\contrib\hbcurl\hbcurl.ch"

//----------------------------------------------------------------------------//

function Main()

    local oChatgpt := TOpenAI():New()

    // oChatgpt:SendImageURL( "https://forums.fivetechsupport.com/styles/prosilver/imageset/site_logo.gif" )
    // oChatgpt:SendImage( "../bitmaps/logo/fivepowergm5.jpg" )
    oChatgpt:Send( "What is the capital of France ?" )

    MsgInfo( oChatgpt:GetValue() )

    oChatgpt:End()

return nil    

//----------------------------------------------------------------------------//

CLASS TOpenAI
    
    DATA   cKey   INIT ""
    DATA   cModel INIT "gpt-4o-mini"
    DATA   cResponse
    DATA   cUrl
    DATA   hCurl
    DATA   nError INIT 0
    DATA   nHttpCode INIT 0

    METHOD New( cKey, cModel )
    METHOD Send( cPrompt )    
    METHOD SendImage( cImageFileName )    
    METHOD SendImageURL( cImageUrl )
    METHOD End()    
    METHOD GetValue( cHKey )    

ENDCLASS        

//----------------------------------------------------------------------------//

METHOD New( cKey, cModel ) CLASS TOpenAI

    if Empty( cKey )
       ::cKey = GetEnv( "OPENAI_API_KEY" )
    endif

    if ! Empty( cModel )
       ::cModel = cModel
    endif
    
    ::cUrl = "https://api.openai.com/v1/chat/completions"
    ::hCurl = curl_easy_init()
    
return Self    

//----------------------------------------------------------------------------//

METHOD End() CLASS TOpenAI

    curl_easy_cleanup( ::hCurl )
    ::hCurl = nil

return nil    

//----------------------------------------------------------------------------//

METHOD GetValue( cHKey ) CLASS TOpenAI

    local aKeys := hb_AParams(), cKey
    local uValue := hb_jsonDecode( ::cResponse )

    hb_default( @cHKey, "content" )

    if cHKey == "content"
       uValue = uValue[ "choices" ][ 1 ][ "message" ][ "content" ]
    endif

    TRY
       for each cKey in aKeys
          if ValType( uValue[ cKey ] ) == "A"
             uValue = uValue[ cKey ][ 1 ][ "choices" ][ 1 ][ "message" ][ "content" ]
          else
             uValue = uValue[ cKey ]
          endif
       next
    CATCH
       XBrowser( uValue )
    END

return uValue

//----------------------------------------------------------------------------//

METHOD Send( cPrompt ) CLASS TOpenAI 

    LOCAL aHeaders, cJson, hRequest := { => }, hMessage := { => }

    curl_easy_setopt( ::hCurl, HB_CURLOPT_POST, .T. )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_URL, ::cUrl )

    aHeaders := { "Content-Type: application/json", ;
                  "Authorization: Bearer " + ::cKey }

    curl_easy_setopt(::hCurl, HB_CURLOPT_HTTPHEADER, aHeaders)
    curl_easy_setopt(::hCurl, HB_CURLOPT_USERNAME, '')
    curl_easy_setopt(::hCurl, HB_CURLOPT_DL_BUFF_SETUP)
    curl_easy_setopt(::hCurl, HB_CURLOPT_SSL_VERIFYPEER, .F.)

    hb_HSet( hRequest, "model", ::cModel )
    hb_HSet( hMessage, "role", "user" )
    hb_HSet( hMessage, "content", cPrompt )

    hRequest[ "messages" ] = { hMessage }
    cJson = hb_jsonEncode( hRequest )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_POSTFIELDS, cJson )
    ::nError = curl_easy_perform( ::hCurl )
    curl_easy_getinfo( ::hCurl, HB_CURLINFO_RESPONSE_CODE, @::nHttpCode )

    if ::nError == HB_CURLE_OK
       ::cResponse = curl_easy_dl_buff_get( ::hCurl )
    else
       ::cResponse := "Error code " + Str( ::nError )
    endif
 
return ::cResponse

//----------------------------------------------------------------------------//

METHOD SendImage( cImageFileName ) CLASS TOpenAI

    local aHeaders, cJson, cBase64Image, hMessage := { => }

    if ! File( cImageFileName )
       MsgAlert( "Image " + cImageFileName + " not found" )
       return nil
    endif

    cBase64Image := hb_base64Encode( memoRead( cImageFileName ) )

    curl_easy_setopt( ::hCurl, HB_CURLOPT_POST, .T. )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_URL, "https://api.openai.com/v1/chat/completions" )

    aHeaders := { "Content-Type: application/json", ;
                  "Authorization: Bearer " + ::cKey }

    curl_easy_setopt( ::hCurl, HB_CURLOPT_HTTPHEADER, aHeaders )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_USERNAME, "" )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_DL_BUFF_SETUP )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_SSL_VERIFYPEER, .F. )

    hb_HSet( hMessage, "role", "user" )
    hb_HSet( hMessage, "content", { ;
        { "type" => "text", "text" => "What is in this image?" }, ;
        { "type" => "image_url", ;
          "image_url" => { "url" => "data:image/jpeg;base64," + cBase64Image } } } )

    cJson := hb_jsonEncode( { "model" => ::cModel, ;
                              "messages" => { hMessage } } )

    curl_easy_setopt( ::hCurl, HB_CURLOPT_POSTFIELDS, cJson )

    ::nError = curl_easy_perform( ::hCurl )
    curl_easy_getinfo( ::hCurl, HB_CURLINFO_RESPONSE_CODE, @::nHttpCode )

    if ::nError == HB_CURLE_OK
       ::cResponse = curl_easy_dl_buff_get( ::hCurl )
    else
       ::cResponse = "Error code " + Str( ::nError )
    endif

return ::cResponse

//----------------------------------------------------------------------------//

METHOD SendImageURL( cImageUrl ) CLASS TOpenAI

    local aHeaders, cJson, hRequest := { => }, hMessage := { => }

    curl_easy_setopt( ::hCurl, HB_CURLOPT_POST, .T. )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_URL, ::cUrl )

    aHeaders := { "Content-Type: application/json", ;
                  "Authorization: Bearer " + ::cKey }

    curl_easy_setopt( ::hCurl, HB_CURLOPT_HTTPHEADER, aHeaders )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_USERNAME, "" )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_DL_BUFF_SETUP )
    curl_easy_setopt( ::hCurl, HB_CURLOPT_SSL_VERIFYPEER, .F. )

    hb_HSet( hRequest, "model", ::cModel )
    hb_HSet( hMessage, "role", "user" )

    hb_HSet( hMessage, "content", { ;
        { "type" => "text", "text" => "What's in this image?" }, ;
        { "type" => "image_url", "image_url" => { "url" => cImageUrl } } } )

    hRequest[ "messages" ] = { hMessage }

    cJson = hb_jsonEncode( hRequest )

    curl_easy_setopt( ::hCurl, HB_CURLOPT_POSTFIELDS, cJson )

    ::nError = curl_easy_perform( ::hCurl )
    curl_easy_getinfo( ::hCurl, HB_CURLINFO_RESPONSE_CODE, @::nHttpCode )

    if ::nError == HB_CURLE_OK
       ::cResponse = curl_easy_dl_buff_get( ::hCurl )
    else
       ::cResponse = "Error code " + Str( ::nError )
    endif

return ::cResponse
Mais informações, ou novas versões, provavelmente no fórum oficial do fivewin.

Nota: nesta data/horário, o site mostra aviso de manutenção.

API Deepseek

Enviado: 01 Fev 2025 05:23
por developer
Qual é o substituto de TRY/CATCH/END no Harbour?
E o que substitui o XBROWSER() no Harbour?
Obrigado

API Deepseek

Enviado: 01 Fev 2025 07:07
por alxsts
Olá!
developer escreveu:Qual é o substituto de TRY/CATCH/END no Harbour?

Código: Selecionar todos

BEGIN SEQUENCE
        <statements>...
     [BREAK [<exp>]]
        <statements>...
     [RECOVER [USING <idVar>]]
        <statements>...
     [DEFAULT]
  END [SEQUENCE]
Na verdade, o xHarbour implementou um #translate do comando acima, que resultou em Try/Catch/End try. Tem na documentação. O comando acima funciona no xHarbour também.
developer escreveu:o que substitui o XBROWSER() no Harbour?
Esta função pertence a alguma biblioteca gráfica. No ambiente Harbour, que é console, corresponde à Classe TBrowse.

Obs: para assuntos diferentes do tópico corrente, abra um novo. Evite desvio de assunto.

API Deepseek

Enviado: 01 Fev 2025 11:29
por Ana Mitoooo

Código: Selecionar todos

#xcommand TRY => BEGIN SEQUENCE WITH { |o| Break( o ) }
#xcommand CATCH [<!oErr!>] => RECOVER [USING <oErr>] <-oErr->
#xcommand FINALLY => ALWAYS
developer escreveu:Qual é o substituto de TRY/CATCH/END no Harbour?
E o que substitui o XBROWSER() no Harbour?
Obrigado

API Deepseek

Enviado: 01 Fev 2025 18:02
por developer
Obrigado a todos pela ajuda, ainda não consegui decifrar este xbrowser()
Obs: para assuntos diferentes do tópico corrente, abra um novo. Evite desvio de assunto.
Bem, não acho que estou desviando do assunto pois estes comandos e função constam no código da primeira mensagem do José... o xbrowser() vem do FiveWin e estou tentando testar a rotina que ele publicou, não consegui em virtude disso, não sei se basta trocar por browse(), estou testando mas não consegui ainda uma chave da API conforme indicado pois está caindo aqui: https://chat.deepseek.com/503/

API Deepseek

Enviado: 08 Mar 2025 17:49
por developer
Só queria confirmar que o site do DeepSeek voltou a funcionar, agora é possível conseguir uma chave API.

Uma coisa que ainda não consegui resolver é saber como substituir a função XBROWSER() do Fivewin por equivalente em Harbour Vanilla.

Alguém tem algum manual do Fivewin onde explica o que faz?

API Deepseek

Enviado: 08 Mar 2025 21:35
por JoséQuintas
Boa pergunta, apenas repassei o fonte, sem olhar o conteúdo.

Pelo uso, tá parecendo pra mostrar o valor, no caso de erro.

Talvez Alert( hb_ValToExp( xValue ) )

Nota: No manual do fivewin não encontrei.

API Deepseek

Enviado: 09 Mar 2025 21:20
por developer
A sua sugestão foi ótima, havia me esquecido de usar esta função.

Pelo que pesquisei o XBroswser() é uma função bem completa do Fivewin, tem muito uso e é como se fosse um Browse() com asteróides, pode mostrar vários tipos de dado de forma automática.

Quanto ao DeepSeek, deixei de lado, tem mudado constantemente, nem havia resolvido os primeiros problemas e ele mudaram a API, refiz para nova API e mudaram de novo... tá parecendo NFe kkkkkkkkk
Screenshot_2.jpg