|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import os |
| 4 | +import sys |
| 5 | +from datetime import datetime |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any, Literal |
| 8 | + |
| 9 | +import logfire |
| 10 | +from logfire.experimental.query_client import AsyncLogfireQueryClient |
| 11 | +from pydantic import BaseModel, TypeAdapter |
| 12 | +from pydantic_ai import Agent, format_as_xml |
| 13 | + |
| 14 | +sys.path.append(str(Path(__file__).parent.parent)) |
| 15 | + |
| 16 | +from app import agent |
| 17 | + |
| 18 | +read_token = os.environ['LOGFIRE_READ_TOKEN'] |
| 19 | +logfire.configure(environment='evals') |
| 20 | +logfire.instrument_pydantic_ai() |
| 21 | + |
| 22 | +auto_annotation_agent = Agent( |
| 23 | + 'anthropic:claude-opus-4-0', |
| 24 | + instructions=""" |
| 25 | +Your task is to build a system prompt for an agent (the evals agent) which will evaluate the performance of another |
| 26 | +agent and provide feedback on its performance. |
| 27 | +
|
| 28 | +You should return the system prompt for the evals agent ONLY. |
| 29 | +""", |
| 30 | +) |
| 31 | + |
| 32 | + |
| 33 | +class RunFeedback(BaseModel): |
| 34 | + reaction: Literal['positive', 'negative'] | None |
| 35 | + comment: str | None |
| 36 | + |
| 37 | + |
| 38 | +class AgentRunSummary(BaseModel): |
| 39 | + prompt: str |
| 40 | + context: Any |
| 41 | + output: Any |
| 42 | + feedback: RunFeedback | None = None |
| 43 | + |
| 44 | + |
| 45 | +count_runs_query = "select count(*) from records where message = 'time_range_agent run'" |
| 46 | +runs_query = """ |
| 47 | +select |
| 48 | + trace_id, |
| 49 | + span_id, |
| 50 | + 'time timestamp: ' || created_at as context, |
| 51 | + attributes->'all_messages_events'->1->>'content' as prompt, |
| 52 | + attributes->'final_result' as output |
| 53 | +from records |
| 54 | +where message = 'time_range_agent run' |
| 55 | +""" |
| 56 | +feedback_query = """ |
| 57 | +select |
| 58 | + trace_id, |
| 59 | + parent_span_id, |
| 60 | + attributes->>'Annotation' as reaction, |
| 61 | + attributes->>'logfire.feedback.comment' as comment |
| 62 | +from records |
| 63 | +where kind='annotation' and attributes->>'logfire.feedback.name'='Annotation' |
| 64 | +""" |
| 65 | +min_count = 1 |
| 66 | + |
| 67 | + |
| 68 | +async def get_runs() -> None | list[AgentRunSummary]: |
| 69 | + min_timestamp = datetime(2025, 7, 2) |
| 70 | + async with AsyncLogfireQueryClient(read_token) as client: |
| 71 | + c = await client.query_json(sql=count_runs_query, min_timestamp=min_timestamp) |
| 72 | + count = c['columns'][0]['values'][0] |
| 73 | + if count < min_count: |
| 74 | + print(f'Insufficient runs ({count})') |
| 75 | + return |
| 76 | + |
| 77 | + r = await client.query_json_rows(sql=feedback_query, min_timestamp=min_timestamp) |
| 78 | + feedback_lookup: dict[str, Any] = { |
| 79 | + f'{row["trace_id"]}-{row["parent_span_id"]}': RunFeedback(**row) for row in r['rows'] |
| 80 | + } |
| 81 | + |
| 82 | + r = await client.query_json_rows(sql=runs_query, min_timestamp=min_timestamp) |
| 83 | + runs: list[AgentRunSummary] = [] |
| 84 | + with_feedback = 0 |
| 85 | + for row in r['rows']: |
| 86 | + key = f'{row["trace_id"]}-{row["span_id"]}' |
| 87 | + if feedback := feedback_lookup.get(key): |
| 88 | + row['feedback'] = feedback |
| 89 | + with_feedback += 1 |
| 90 | + runs.append(AgentRunSummary(**row)) |
| 91 | + |
| 92 | + logfire.info(f'Found {len(runs)} runs, {with_feedback} with feedback') |
| 93 | + return runs |
| 94 | + |
| 95 | + |
| 96 | +async def generate_evals_prompt( |
| 97 | + name: str, instrunctions: str, output_type: type[Any] | None, runs: list[AgentRunSummary] |
| 98 | +) -> str: |
| 99 | + data: dict[str, Any] = {'agent_name': name, 'agent_instructions': instrunctions} |
| 100 | + if output_type is not None: |
| 101 | + data['output_schema'] = json.dumps(TypeAdapter(output_type).json_schema(), indent=2) |
| 102 | + data['agent_runs'] = [run.model_dump(exclude_none=True) for run in runs] |
| 103 | + prompt = format_as_xml(data, include_root_tag=False) |
| 104 | + r = await auto_annotation_agent.run(prompt) |
| 105 | + return r.output |
| 106 | + |
| 107 | + |
| 108 | +async def main(): |
| 109 | + runs = await get_runs() |
| 110 | + if runs: |
| 111 | + prompt = await generate_evals_prompt( |
| 112 | + 'time_range_agent', |
| 113 | + agent.instrunctions, |
| 114 | + agent.TimeRangeResponse, # type: ignore |
| 115 | + runs, |
| 116 | + ) |
| 117 | + prompt_path = Path(__file__).parent / 'eval_agent_prompt.txt' |
| 118 | + prompt_path.write_text(prompt) |
| 119 | + print(f'prompt written to {prompt_path}') |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == '__main__': |
| 123 | + asyncio.run(main()) |
0 commit comments