pareaud commited on
Commit
a0498f6
·
verified ·
1 Parent(s): afee056

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -26
app.py CHANGED
@@ -13,8 +13,26 @@ api_key = "sk-proj-HYw82rX0O01CJrobRFj13r3BFxN3H1qOfswMSK1NGtGpfNyylWzMV_lQXw8Ee
13
 
14
  client = OpenAI(api_key=api_key)
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  # ------------------------------------------------------------------
17
- # 2 — Définition du schéma JSON (outil) à respecter
18
  # ------------------------------------------------------------------
19
 
20
  extraction_schema: Dict[str, Any] = {
@@ -61,50 +79,64 @@ extraction_schema: Dict[str, Any] = {
61
  },
62
  }
63
 
64
- # Emballage dans la structure tool
65
  TOOLS = [{"type": "function", "function": extraction_schema}]
66
 
67
  SYSTEM_PROMPT = (
68
  "Tu es un assistant administratif. À partir d’un texte mal rédigé, "
69
  "tu dois extraire les informations personnelles sous forme de JSON "
70
- "conforme au schéma fourni. Ne réponds JAMAIS hors JSON."
 
71
  )
72
 
73
  # ------------------------------------------------------------------
74
- # 3 — Fonction d'extraction « backend »
75
  # ------------------------------------------------------------------
76
 
77
  def extraire_infos(texte: str) -> str:
78
- """Appelle le modèle et renvoie un JSON indenté ou un message d'erreur."""
 
 
 
 
 
79
 
80
- try:
81
- # Première (et unique) requête : on force le choix de l'outil
82
  response = client.chat.completions.create(
83
- model="gpt-4o-mini", # ou "gpt-3.5-turbo-0125"
84
  temperature=0,
85
- messages=[
86
- {"role": "system", "content": SYSTEM_PROMPT},
87
- {"role": "user", "content": texte},
88
- ],
89
  tools=TOOLS,
90
- tool_choice={"type": "function", "function": {"name": "extract_user_info"}},
 
 
 
91
  )
92
 
93
  choice = response.choices[0]
94
- if choice.finish_reason != "tool_calls":
95
- # Le modèle n'a pas utilisé l'outil : on renvoie le contenu brut
96
- return choice.message.content or "(Aucun contenu renvoyé)"
97
-
98
- # Récupère les arguments du premier tool_call
99
- args_str = choice.message.tool_calls[0].function.arguments
100
- parsed = json.loads(args_str)
101
- return json.dumps(parsed, indent=2, ensure_ascii=False)
 
 
 
 
 
 
 
 
102
 
103
- except Exception as e:
104
- return f"❌ Erreur : {e}"
 
 
105
 
106
  # ------------------------------------------------------------------
107
- # 4 — Interface Gradio
108
  # ------------------------------------------------------------------
109
 
110
  texte_exemple = (
@@ -117,7 +149,10 @@ texte_exemple = (
117
  )
118
 
119
  with gr.Blocks(title="Extracteur intelligent de données CERFA") as demo:
120
- gr.Markdown("Copie‑colle un texte mal écrit contenant des infos personnelles.\n" "L'IA le transforme en JSON prêt pour l'administration.")
 
 
 
121
 
122
  input_box = gr.Textbox(
123
  lines=14,
@@ -131,8 +166,9 @@ with gr.Blocks(title="Extracteur intelligent de données CERFA") as demo:
131
  extract_btn.click(extraire_infos, input_box, output_box)
132
 
133
  # ------------------------------------------------------------------
134
- # 5 — Lancement
135
  # ------------------------------------------------------------------
136
 
137
  if __name__ == "__main__":
138
  demo.launch()
 
 
13
 
14
  client = OpenAI(api_key=api_key)
15
 
16
+  :
17
+ export OPENAI_API_KEY=sk-...
18
+ pip install openai>=1.0.0 gradio
19
+ """
20
+
21
+ import os
22
+ import json
23
+ from typing import Dict, Any
24
+
25
+ import gradio as gr
26
+ from openai import OpenAI
27
+
28
+ # ------------------------------------------------------------------
29
+ # 1 — Initialisation du client OpenAI
30
+ # ------------------------------------------------------------------
31
+
32
+ client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
33
+
34
  # ------------------------------------------------------------------
35
+ # 2 — Définition du schéma JSON (outil)
36
  # ------------------------------------------------------------------
37
 
38
  extraction_schema: Dict[str, Any] = {
 
79
  },
80
  }
81
 
 
82
  TOOLS = [{"type": "function", "function": extraction_schema}]
83
 
84
  SYSTEM_PROMPT = (
85
  "Tu es un assistant administratif. À partir d’un texte mal rédigé, "
86
  "tu dois extraire les informations personnelles sous forme de JSON "
87
+ "conforme au schéma fourni. Ne réponds JAMAIS hors JSON. "
88
+ "Utilise IMPÉRATIVEMENT l'outil extract_user_info."
89
  )
90
 
91
  # ------------------------------------------------------------------
92
+ # 3 — Fonction d'extraction avec relance forcée
93
  # ------------------------------------------------------------------
94
 
95
  def extraire_infos(texte: str) -> str:
96
+ """Renvoie le JSON extrait ou une erreur si l’outil n’est jamais appelé."""
97
+
98
+ messages = [
99
+ {"role": "system", "content": SYSTEM_PROMPT},
100
+ {"role": "user", "content": texte},
101
+ ]
102
 
103
+ for attempt in range(2): # on tente deux fois maximum
 
104
  response = client.chat.completions.create(
105
+ model="gpt-4o-mini", # ou gpt-3.5-turbo-0125
106
  temperature=0,
107
+ messages=messages,
 
 
 
108
  tools=TOOLS,
109
+ tool_choice={
110
+ "type": "function",
111
+ "function": {"name": "extract_user_info"},
112
+ },
113
  )
114
 
115
  choice = response.choices[0]
116
+ if choice.finish_reason == "tool_calls":
117
+ args_str = choice.message.tool_calls[0].function.arguments
118
+ parsed = json.loads(args_str)
119
+ return json.dumps(parsed, indent=2, ensure_ascii=False)
120
+
121
+ # Pas d'appel d'outil : on renforce l'instruction et on réessaie
122
+ messages.insert(
123
+ 0,
124
+ {
125
+ "role": "system",
126
+ "content": (
127
+ "⚠️ Utilise OBLIGATOIREMENT l'outil extract_user_info et "
128
+ "ne renvoie jamais de texte libre."
129
+ ),
130
+ },
131
+ )
132
 
133
+ return (
134
+ "❌ Erreur : le modèle n'a pas renvoyé d'appel d'outil après deux "
135
+ "tentatives."
136
+ )
137
 
138
  # ------------------------------------------------------------------
139
+ # 4 — Interface Gradio
140
  # ------------------------------------------------------------------
141
 
142
  texte_exemple = (
 
149
  )
150
 
151
  with gr.Blocks(title="Extracteur intelligent de données CERFA") as demo:
152
+ gr.Markdown(
153
+ "Copie-colle un texte mal écrit contenant des infos personnelles.\n"
154
+ "L'IA le transforme en JSON prêt pour l'administration."
155
+ )
156
 
157
  input_box = gr.Textbox(
158
  lines=14,
 
166
  extract_btn.click(extraire_infos, input_box, output_box)
167
 
168
  # ------------------------------------------------------------------
169
+ # 5 — Lancement
170
  # ------------------------------------------------------------------
171
 
172
  if __name__ == "__main__":
173
  demo.launch()
174
+