File size: 2,331 Bytes
829827d
0a756b0
 
09bc8bd
 
0a756b0
 
 
 
09bc8bd
6848052
0deea66
0a756b0
 
 
816a5d4
0a756b0
 
 
 
 
 
6848052
09bc8bd
0a756b0
 
 
 
09bc8bd
 
0a756b0
 
9f31e97
6848052
0a756b0
 
6848052
09bc8bd
6848052
09bc8bd
0a756b0
09bc8bd
0a756b0
 
 
 
 
 
 
e21292c
0a756b0
 
 
 
 
 
 
 
 
3818f5a
e21292c
09bc8bd
9f31e97
6848052
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import openai
import os

# Configura la tua chiave API in modo sicuro
api_key = os.getenv("OPENAI_API_KEY")  # Imposta la chiave come variabile d'ambiente

if not api_key:
    raise ValueError("Chiave API OpenAI non trovata. Assicurati di aver impostato OPENAI_API_KEY.")

# Crea il client utilizzando la chiave API
openai.api_key = api_key  # Usa direttamente api_key

def riassumi_testo(testo, max_token_riassunto):
    """
    Utilizza l'API di OpenAI per riassumere un testo con un numero massimo di token specificato.

    :param testo: Il testo da riassumere
    :param max_token_riassunto: Numero massimo di token per il riassunto
    :return: Riassunto del testo
    """
    try:
        # Esegui la chiamata all'API di OpenAI
        risposta = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",  # Modello specifico
            messages=[
                {"role": "system", "content": "Sei un assistente che riassume i testi in modo chiaro e conciso."},
                {"role": "user", "content": f"Riassumi il seguente testo: {testo}"}
            ],
            max_tokens=max_token_riassunto,  # Limita i token
            temperature=0.5,  # Imposta la creatività
        )

        # Estrai il riassunto dalla risposta correttamente
        riassunto = risposta['choices'][0]['message']['content']  # Accesso corretto al contenuto
        return riassunto

    except openai.InvalidRequestError as e:  # Gestisci errore nella richiesta
        return f"Errore nella richiesta: {e}"
    except openai.AuthenticationError:
        return "Errore di autenticazione: chiave API non valida."
    except Exception as e:
        return f"Errore durante il riassunto: {str(e)}"

# Test del codice
if __name__ == "__main__":
    testo_originale = (
        "OpenAI ha sviluppato modelli linguistici avanzati come GPT-3.5 che sono in grado di generare testo, tradurre lingue, "
        "e risolvere problemi complessi. Questi modelli possono essere utilizzati in molte applicazioni, inclusi chatbot, "
        "strumenti di scrittura e sistemi di supporto decisionale."
    )

    max_token = 50  # Numero massimo di token per il riassunto
    riassunto = riassumi_testo(testo_originale, max_token)

    print("Testo originale:")
    print(testo_originale)
    print("\nRiassunto:")
    print(riassunto)