SergeyO7 commited on
Commit
b63180f
·
verified ·
1 Parent(s): feac674

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -27
app.py CHANGED
@@ -12,25 +12,30 @@ import base64
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
- LANGFUSE_PUBLIC_KEY="pk-lf-7f0677a5-09f7-4508-88a2-bf7f44ee172c"
16
- LF_SECRET_KEY = os.environ.get("LANGFUSE_SECRET_KEY")
17
- if LF_SECRET_KEY is None:
18
- raise EnvironmentError("LANGFUSE_SECRET_KEY environment variable is not set.")
19
- LANGFUSE_AUTH=base64.b64encode(f"{LANGFUSE_PUBLIC_KEY}:{LF_SECRET_KEY}".encode()).decode()
20
 
21
- from opentelemetry.sdk.trace import TracerProvider
22
- from openinference.instrumentation.smolagents import SmolagentsInstrumentor
23
- from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
24
- from opentelemetry.sdk.trace.export import SimpleSpanProcessor
25
 
26
- os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://cloud.langfuse.com/api/public/otel" # EU data region
27
- os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}"
 
 
 
28
 
 
 
 
 
29
 
30
- trace_provider = TracerProvider()
31
- trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint="https://cloud.langfuse.com/api/public/otel")))
32
 
33
- SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)
 
 
 
 
34
 
35
  async def fetch_questions(session: aiohttp.ClientSession, questions_url: str) -> list:
36
  """Fetch questions asynchronously."""
@@ -66,6 +71,20 @@ async def submit_answers(session: aiohttp.ClientSession, submit_url: str, submis
66
  print(f"An unexpected error occurred during submission: {e}")
67
  return None
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  async def run_and_submit_all(profile: gr.OAuthProfile | None):
70
  """
71
  Fetches all questions asynchronously, runs the MagAgent on them, submits all answers,
@@ -104,22 +123,35 @@ async def run_and_submit_all(profile: gr.OAuthProfile | None):
104
  return "Fetched questions list is empty or invalid format.", None
105
 
106
  # 3. Run Agent on Questions
 
 
 
107
  results_log = []
108
  answers_payload = []
 
109
  print(f"Running agent on {len(questions_data)} questions...")
110
- for item in questions_data:
111
- task_id = item.get("task_id")
112
- question_text = item.get("question")
113
- if not task_id or question_text is None:
114
- print(f"Skipping item with missing task_id or question: {item}")
115
- continue
116
- try:
117
- submitted_answer = await agent(question_text)
118
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
119
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
120
- except Exception as e:
121
- print(f"Error running agent on task {task_id}: {e}")
122
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
123
 
124
  if not answers_payload:
125
  print("Agent did not produce any answers to submit.")
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
15
 
16
+ # Rate limiting configuration
17
+ MAX_CONCURRENT_REQUESTS = 5 # Adjust based on performance needs
18
+ REQUEST_DELAY = 2.0 # 2 seconds delay to meet 30 RPM
 
19
 
20
+ # LANGFUSE_PUBLIC_KEY="pk-lf-7f0677a5-09f7-4508-88a2-bf7f44ee172c"
21
+ # LF_SECRET_KEY = os.environ.get("LANGFUSE_SECRET_KEY")
22
+ # if LF_SECRET_KEY is None:
23
+ # raise EnvironmentError("LANGFUSE_SECRET_KEY environment variable is not set.")
24
+ # LANGFUSE_AUTH=base64.b64encode(f"{LANGFUSE_PUBLIC_KEY}:{LF_SECRET_KEY}".encode()).decode()
25
 
26
+ # from opentelemetry.sdk.trace import TracerProvider
27
+ # from openinference.instrumentation.smolagents import SmolagentsInstrumentor
28
+ # from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
29
+ # from opentelemetry.sdk.trace.export import SimpleSpanProcessor
30
 
31
+ # os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://cloud.langfuse.com/api/public/otel" # EU data region
32
+ # os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}"
33
 
34
+
35
+ # trace_provider = TracerProvider()
36
+ # trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint="https://cloud.langfuse.com/api/public/otel")))
37
+
38
+ # SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)
39
 
40
  async def fetch_questions(session: aiohttp.ClientSession, questions_url: str) -> list:
41
  """Fetch questions asynchronously."""
 
71
  print(f"An unexpected error occurred during submission: {e}")
72
  return None
73
 
74
+ async def process_question(agent, question_text: str, task_id: str, semaphore: asyncio.Semaphore, results_log: list):
75
+ """Process a single question with rate limiting."""
76
+ async with semaphore:
77
+ try:
78
+ submitted_answer = await agent(question_text)
79
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
80
+ return {"task_id": task_id, "submitted_answer": submitted_answer}
81
+ except Exception as e:
82
+ print(f"Error running agent on task {task_id}: {e}")
83
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
84
+ return None
85
+ finally:
86
+ await asyncio.sleep(REQUEST_DELAY) # Enforce delay after each request
87
+
88
  async def run_and_submit_all(profile: gr.OAuthProfile | None):
89
  """
90
  Fetches all questions asynchronously, runs the MagAgent on them, submits all answers,
 
123
  return "Fetched questions list is empty or invalid format.", None
124
 
125
  # 3. Run Agent on Questions
126
+
127
+ # Initialize semaphore and results log
128
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
129
  results_log = []
130
  answers_payload = []
131
+
132
  print(f"Running agent on {len(questions_data)} questions...")
133
+
134
+ tasks = [
135
+ process_question(agent, item["question"], item["task_id"], semaphore, results_log)
136
+ for item in questions_data
137
+ if item.get("task_id") and item.get("question") is not None
138
+ ]
139
+ results = await asyncio.gather(*tasks)
140
+ answers_payload = [r for r in results if r is not None]
141
+
142
+ # for item in questions_data:
143
+ # task_id = item.get("task_id")
144
+ # question_text = item.get("question")
145
+ # if not task_id or question_text is None:
146
+ # print(f"Skipping item with missing task_id or question: {item}")
147
+ # continue
148
+ # try:
149
+ # submitted_answer = await agent(question_text)
150
+ # answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
151
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
152
+ # except Exception as e:
153
+ # print(f"Error running agent on task {task_id}: {e}")
154
+ # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
155
 
156
  if not answers_payload:
157
  print("Agent did not produce any answers to submit.")