|
| 1 | +import time |
| 2 | +from dataclasses import dataclass, field |
| 3 | +from typing import List, Any, Union, Dict |
| 4 | + |
| 5 | +from openai.types.chat import ChatCompletionMessageParam, ChatCompletionMessage |
| 6 | +from capabilities import Capability |
| 7 | +from capabilities.capability import capabilities_to_action_model |
| 8 | +from capabilities.http_request import HTTPRequest |
| 9 | +from capabilities.record_note import RecordNote |
| 10 | +from capabilities.submit_flag import SubmitFlag |
| 11 | +from usecases.web_api_testing.prompt_engineer import PromptEngineer, PromptStrategy |
| 12 | +from utils import LLMResult, tool_message, ui |
| 13 | +from utils.configurable import parameter |
| 14 | +from utils.openai.openai_lib import OpenAILib |
| 15 | +from rich.panel import Panel |
| 16 | +from usecases import use_case |
| 17 | +from usecases.usecase.roundbased import RoundBasedUseCase |
| 18 | +import pydantic_core |
| 19 | + |
| 20 | +Prompt = List[Union[ChatCompletionMessage, ChatCompletionMessageParam]] |
| 21 | +Context = Any |
| 22 | + |
| 23 | + |
| 24 | +@use_case("simple_web_api_documentation", "Minimal implementation of a web api documentation use case") |
| 25 | +@dataclass |
| 26 | +class SimpleWebAPIDocumentation(RoundBasedUseCase): |
| 27 | + llm: OpenAILib |
| 28 | + host: str = parameter(desc="The host to test", default="https://jsonplaceholder.typicode.com") |
| 29 | + _prompt_history: Prompt = field(default_factory=list) |
| 30 | + _context: Context = field(default_factory=lambda: {"notes": list()}) |
| 31 | + _capabilities: Dict[str, Capability] = field(default_factory=dict) |
| 32 | + _all_http_methods_found: bool = False |
| 33 | + # Parameter specifying the pattern description for expected HTTP methods in the API response |
| 34 | + http_method_description: str = parameter( |
| 35 | + desc="Pattern description for expected HTTP methods in the API response", |
| 36 | + default="A string that represents an HTTP method (e.g., 'GET', 'POST', etc.)." |
| 37 | + ) |
| 38 | + |
| 39 | + # Parameter specifying the template used to format HTTP methods in API requests |
| 40 | + http_method_template: str = parameter( |
| 41 | + desc="Template used to format HTTP methods in API requests. The {method} placeholder will be replaced by actual HTTP method names.", |
| 42 | + default="{method} request" |
| 43 | + ) |
| 44 | + |
| 45 | + # Parameter specifying the expected HTTP methods as a comma-separated list |
| 46 | + http_methods: str = parameter( |
| 47 | + desc="Comma-separated list of HTTP methods expected to be used in the API response.", |
| 48 | + default="GET,POST,PUT,PATCH,DELETE" |
| 49 | + ) |
| 50 | + def init(self): |
| 51 | + super().init() |
| 52 | + self._prompt_history.append( |
| 53 | + { |
| 54 | + "role": "system", |
| 55 | + "content": f"You're tasked with documenting the REST APIs of a website hosted at {self.host}. " |
| 56 | + f"Your main goal is to comprehensively explore the APIs endpoints and responses, and then document your findings in form of a OpenAPI specification." |
| 57 | + f" This thorough documentation will facilitate analysis later on.\n" |
| 58 | + f"Maintain meticulousness in documenting your observations as you traverse the APIs. This will streamline the documentation process.\n" |
| 59 | + f"Avoid resorting to brute-force methods. All essential information should be accessible through the API endpoints.\n" |
| 60 | + |
| 61 | + }) |
| 62 | + self.prompt_engineer = PromptEngineer( |
| 63 | + strategy=PromptStrategy.CHAIN_OF_THOUGHT, |
| 64 | + api_key=self.llm.api_key, |
| 65 | + history=self._prompt_history) |
| 66 | + |
| 67 | + self._context["host"] = self.host |
| 68 | + sett = set(self.http_method_template.format(method=method) for method in self.http_methods.split(",")) |
| 69 | + self._capabilities = { |
| 70 | + "submit_http_method": SubmitFlag(self.http_method_description, |
| 71 | + sett, |
| 72 | + success_function=self.all_http_methods_found), |
| 73 | + "http_request": HTTPRequest(self.host), |
| 74 | + "record_note": RecordNote(self._context["notes"]), |
| 75 | + } |
| 76 | + |
| 77 | + def all_http_methods_found(self): |
| 78 | + self.console.print(Panel("All HTTP methods found! Congratulations!", title="system")) |
| 79 | + self._all_http_methods_found = True |
| 80 | + |
| 81 | + def perform_round(self, turn: int): |
| 82 | + |
| 83 | + |
| 84 | + with self.console.status("[bold green]Asking LLM for a new command..."): |
| 85 | + # generate prompt |
| 86 | + prompt = self.prompt_engineer.generate_prompt() |
| 87 | + |
| 88 | + tic = time.perf_counter() |
| 89 | + response, completion = self.llm.instructor.chat.completions.create_with_completion(model=self.llm.model, |
| 90 | + messages=prompt, |
| 91 | + response_model=capabilities_to_action_model( |
| 92 | + self._capabilities)) |
| 93 | + toc = time.perf_counter() |
| 94 | + |
| 95 | + message = completion.choices[0].message |
| 96 | + |
| 97 | + tool_call_id = message.tool_calls[0].id |
| 98 | + command = pydantic_core.to_json(response).decode() |
| 99 | + self.console.print(Panel(command, title="assistant")) |
| 100 | + |
| 101 | + self._prompt_history.append(message) |
| 102 | + content = completion.choices[0].message.content |
| 103 | + |
| 104 | + #print(f'message:{message}') |
| 105 | + answer = LLMResult(content, str(prompt), |
| 106 | + content, toc - tic, completion.usage.prompt_tokens, |
| 107 | + completion.usage.completion_tokens) |
| 108 | + #print(f'answer: {answer}') |
| 109 | + |
| 110 | + with self.console.status("[bold green]Executing that command..."): |
| 111 | + result = response.execute() |
| 112 | + |
| 113 | + self.console.print(Panel(result, title="tool")) |
| 114 | + result_str = self.parse_http_status_line(result) |
| 115 | + self._prompt_history.append(tool_message(result_str, tool_call_id)) |
| 116 | + |
| 117 | + self.log_db.add_log_query(self._run_id, turn, command, result, answer) |
| 118 | + return self._all_http_methods_found |
| 119 | + |
| 120 | + def parse_http_status_line(self, status_line): |
| 121 | + if status_line is None or status_line == "Not a valid flag": |
| 122 | + return status_line |
| 123 | + else: |
| 124 | + # Split the status line into components |
| 125 | + parts = status_line.split(' ', 2) |
| 126 | + |
| 127 | + # Check if the parts are at least three in number |
| 128 | + if len(parts) >= 3: |
| 129 | + protocol = parts[0] # e.g., "HTTP/1.1" |
| 130 | + status_code = parts[1] # e.g., "200" |
| 131 | + status_message = parts[2].split("\r\n")[0] # e.g., "OK" |
| 132 | + print(f'status code:{status_code}, status msg:{status_message}') |
| 133 | + return str(status_code +" " + status_message ) |
| 134 | + else: |
| 135 | + raise ValueError("Invalid HTTP status line") |
| 136 | + |
| 137 | + |
| 138 | + |
| 139 | + |
0 commit comments