Tejasva commited on
Commit ·
4b48a6b
1
Parent(s): d68f67f
minor fixes
Browse files- inference.py +22 -22
inference.py
CHANGED
|
@@ -20,22 +20,22 @@ logger = logging.getLogger(__name__)
|
|
| 20 |
|
| 21 |
def setup_openai_client() -> tuple[OpenAI, str]:
|
| 22 |
"""Initialize OpenAI client from environment variables."""
|
| 23 |
-
api_base_url = os.getenv('API_BASE_URL', 'https://router.huggingface.co/v1')
|
| 24 |
-
model_name = os.getenv('MODEL_NAME', 'meta-llama/Llama-3-8b-instruct')
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
| 30 |
raise ValueError("HF_TOKEN environment variable is required")
|
| 31 |
-
|
| 32 |
-
# Initialize OpenAI client with base_url and api_key
|
| 33 |
client = OpenAI(
|
| 34 |
-
api_key=
|
| 35 |
-
base_url=
|
| 36 |
)
|
| 37 |
-
|
| 38 |
-
return client,
|
| 39 |
|
| 40 |
def create_adaptive_prompt(observation: Dict[str, Any], step_type: str, agent_state: AgentState) -> str:
|
| 41 |
"""Create adaptive prompt based on agent learning state."""
|
|
@@ -142,11 +142,11 @@ def create_action_from_response(step_type: str, response: AgentResponse) -> Acti
|
|
| 142 |
suggested_fix=response.fix if step_type == 'fix' else None
|
| 143 |
)
|
| 144 |
|
| 145 |
-
def run_llm_inference(client: OpenAI,
|
| 146 |
"""Run LLM inference with given prompt."""
|
| 147 |
try:
|
| 148 |
response = client.chat.completions.create(
|
| 149 |
-
model=
|
| 150 |
messages=[
|
| 151 |
{"role": "system", "content": "You are a professional code reviewer. Always respond in valid JSON format with confidence and reasoning."},
|
| 152 |
{"role": "user", "content": prompt}
|
|
@@ -231,15 +231,15 @@ def update_agent_state(agent_state: AgentState, episode_reward: float, feedback:
|
|
| 231 |
|
| 232 |
return agent_state
|
| 233 |
|
| 234 |
-
def run_episode(env: CodeGuardianEnv, client: OpenAI,
|
| 235 |
"""Run a single episode and return total reward with episode history."""
|
| 236 |
obs = env.reset()
|
| 237 |
episode_reward = 0.0
|
| 238 |
episode_history = []
|
| 239 |
step_count = 0
|
| 240 |
|
| 241 |
-
print(f"START: Episode {agent_state.episode + 1} - model={
|
| 242 |
-
logger.info(f"[EPISODE START] Episode {agent_state.episode + 1} - model={
|
| 243 |
|
| 244 |
while not env.done:
|
| 245 |
current_step = env.state()['current_step']
|
|
@@ -255,7 +255,7 @@ def run_episode(env: CodeGuardianEnv, client: OpenAI, model_name: str, agent_sta
|
|
| 255 |
|
| 256 |
# Run LLM inference
|
| 257 |
try:
|
| 258 |
-
response_text = run_llm_inference(client,
|
| 259 |
logger.info(f"LLM response: {response_text[:100]}...")
|
| 260 |
except Exception as e:
|
| 261 |
logger.error(f"LLM inference failed: {e}")
|
|
@@ -318,12 +318,12 @@ def train_agent(num_episodes: int = 10) -> AgentState:
|
|
| 318 |
"""Train agent over multiple episodes with policy improvement."""
|
| 319 |
try:
|
| 320 |
# Setup
|
| 321 |
-
client,
|
| 322 |
agent_state = AgentState()
|
| 323 |
all_episodes = []
|
| 324 |
|
| 325 |
-
print(f"START: RL training for {num_episodes} episodes with model: {
|
| 326 |
-
logger.info(f"[TRAINING START] Starting RL training for {num_episodes} episodes with model: {
|
| 327 |
|
| 328 |
# RUN BASELINE FIRST
|
| 329 |
logger.info("\n{'='*60}")
|
|
@@ -344,7 +344,7 @@ def train_agent(num_episodes: int = 10) -> AgentState:
|
|
| 344 |
logger.info(f"{'='*50}")
|
| 345 |
|
| 346 |
env = CodeGuardianEnv()
|
| 347 |
-
episode_reward, episode_history = run_episode(env, client,
|
| 348 |
all_episodes.append({
|
| 349 |
"episode": episode + 1,
|
| 350 |
"reward": episode_reward,
|
|
|
|
| 20 |
|
| 21 |
def setup_openai_client() -> tuple[OpenAI, str]:
|
| 22 |
"""Initialize OpenAI client from environment variables."""
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
print("STEP: Initializing OpenAI client")
|
| 25 |
+
|
| 26 |
+
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
|
| 27 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/Llama-3-8b-instruct")
|
| 28 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 29 |
+
|
| 30 |
+
if not HF_TOKEN:
|
| 31 |
raise ValueError("HF_TOKEN environment variable is required")
|
| 32 |
+
|
|
|
|
| 33 |
client = OpenAI(
|
| 34 |
+
api_key=HF_TOKEN,
|
| 35 |
+
base_url=API_BASE_URL
|
| 36 |
)
|
| 37 |
+
|
| 38 |
+
return client, MODEL_NAME
|
| 39 |
|
| 40 |
def create_adaptive_prompt(observation: Dict[str, Any], step_type: str, agent_state: AgentState) -> str:
|
| 41 |
"""Create adaptive prompt based on agent learning state."""
|
|
|
|
| 142 |
suggested_fix=response.fix if step_type == 'fix' else None
|
| 143 |
)
|
| 144 |
|
| 145 |
+
def run_llm_inference(client: OpenAI, MODEL_NAME: str, prompt: str) -> str:
|
| 146 |
"""Run LLM inference with given prompt."""
|
| 147 |
try:
|
| 148 |
response = client.chat.completions.create(
|
| 149 |
+
model=MODEL_NAME,
|
| 150 |
messages=[
|
| 151 |
{"role": "system", "content": "You are a professional code reviewer. Always respond in valid JSON format with confidence and reasoning."},
|
| 152 |
{"role": "user", "content": prompt}
|
|
|
|
| 231 |
|
| 232 |
return agent_state
|
| 233 |
|
| 234 |
+
def run_episode(env: CodeGuardianEnv, client: OpenAI, MODEL_NAME: str, agent_state: AgentState) -> tuple[float, List[Dict]]:
|
| 235 |
"""Run a single episode and return total reward with episode history."""
|
| 236 |
obs = env.reset()
|
| 237 |
episode_reward = 0.0
|
| 238 |
episode_history = []
|
| 239 |
step_count = 0
|
| 240 |
|
| 241 |
+
print(f"START: Episode {agent_state.episode + 1} - model={MODEL_NAME} task_id={obs.task_id} difficulty={obs.difficulty}")
|
| 242 |
+
logger.info(f"[EPISODE START] Episode {agent_state.episode + 1} - model={MODEL_NAME} task_id={obs.task_id} difficulty={obs.difficulty}")
|
| 243 |
|
| 244 |
while not env.done:
|
| 245 |
current_step = env.state()['current_step']
|
|
|
|
| 255 |
|
| 256 |
# Run LLM inference
|
| 257 |
try:
|
| 258 |
+
response_text = run_llm_inference(client, MODEL_NAME, prompt)
|
| 259 |
logger.info(f"LLM response: {response_text[:100]}...")
|
| 260 |
except Exception as e:
|
| 261 |
logger.error(f"LLM inference failed: {e}")
|
|
|
|
| 318 |
"""Train agent over multiple episodes with policy improvement."""
|
| 319 |
try:
|
| 320 |
# Setup
|
| 321 |
+
client, MODEL_NAME = setup_openai_client()
|
| 322 |
agent_state = AgentState()
|
| 323 |
all_episodes = []
|
| 324 |
|
| 325 |
+
print(f"START: RL training for {num_episodes} episodes with model: {MODEL_NAME}")
|
| 326 |
+
logger.info(f"[TRAINING START] Starting RL training for {num_episodes} episodes with model: {MODEL_NAME}")
|
| 327 |
|
| 328 |
# RUN BASELINE FIRST
|
| 329 |
logger.info("\n{'='*60}")
|
|
|
|
| 344 |
logger.info(f"{'='*50}")
|
| 345 |
|
| 346 |
env = CodeGuardianEnv()
|
| 347 |
+
episode_reward, episode_history = run_episode(env, client, MODEL_NAME, agent_state)
|
| 348 |
all_episodes.append({
|
| 349 |
"episode": episode + 1,
|
| 350 |
"reward": episode_reward,
|