|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import logging |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +from typing import Dict, Optional |
| 9 | + |
| 10 | +import boto3 |
| 11 | +from botocore.exceptions import ClientError |
| 12 | + |
| 13 | +from aws_doc_sdk_examples_tools.doc_gen import DocGen, Snippet |
| 14 | +from aws_doc_sdk_examples_tools.scripts.retry import retry_with_backoff |
| 15 | + |
| 16 | + |
| 17 | +logging.basicConfig(level=logging.INFO) |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +class BedrockRuntime: |
| 22 | + def __init__(self, model_id: str = "us.anthropic.claude-3-7-sonnet-20250219-v1:0"): |
| 23 | + self.client = boto3.client("bedrock-runtime") |
| 24 | + self.model_id = model_id |
| 25 | + self.base_prompt = Path( |
| 26 | + os.path.dirname(__file__), "base_prompt.txt" |
| 27 | + ).read_text() |
| 28 | + self.conversation = [{"role": "user", "content": [{"text": self.base_prompt}]}] |
| 29 | + |
| 30 | + def converse(self, conversation): |
| 31 | + self.conversation.extend(conversation) |
| 32 | + response = self.client.converse( |
| 33 | + modelId=self.model_id, |
| 34 | + messages=self.conversation, |
| 35 | + inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, |
| 36 | + ) |
| 37 | + response_text = response["output"]["message"]["content"][0]["text"] |
| 38 | + return response_text |
| 39 | + |
| 40 | + |
| 41 | +def make_doc_gen(root: Path): |
| 42 | + doc_gen = DocGen.from_root(root) |
| 43 | + doc_gen.collect_snippets() |
| 44 | + return doc_gen |
| 45 | + |
| 46 | + |
| 47 | +@retry_with_backoff(exceptions=(ClientError,), max_retries=10) |
| 48 | +def generate_snippet_description( |
| 49 | + bedrock_runtime: BedrockRuntime, snippet: Snippet, prompt: Optional[str] |
| 50 | +) -> Dict: |
| 51 | + content = ( |
| 52 | + [{"text": prompt}, {"text": snippet.code}] |
| 53 | + if prompt |
| 54 | + else [{"text": snippet.code}] |
| 55 | + ) |
| 56 | + conversation = [ |
| 57 | + { |
| 58 | + "role": "user", |
| 59 | + "content": content, |
| 60 | + } |
| 61 | + ] |
| 62 | + |
| 63 | + response_text = bedrock_runtime.converse(conversation) |
| 64 | + |
| 65 | + try: |
| 66 | + # This assumes the response is JSON, which couples snippet |
| 67 | + # description generation to a specific prompt. |
| 68 | + return json.loads(response_text) |
| 69 | + except Exception as e: |
| 70 | + logger.warning(f"Failed to parse response. Response: {response_text}") |
| 71 | + return {} |
| 72 | + |
| 73 | + |
| 74 | +def generate_descriptions(snippets: Dict[str, Snippet], prompt: Optional[str]): |
| 75 | + runtime = BedrockRuntime() |
| 76 | + results = [] |
| 77 | + for snippet_id, snippet in snippets.items(): |
| 78 | + response = generate_snippet_description(runtime, snippet, prompt) |
| 79 | + results.append(response) |
| 80 | + # Just need a few results for the demo. |
| 81 | + if len(results) == 3: |
| 82 | + break |
| 83 | + print(results) |
| 84 | + |
| 85 | + |
| 86 | +def main(doc_gen_root: Path, prompt: Optional[Path]): |
| 87 | + doc_gen = make_doc_gen(doc_gen_root) |
| 88 | + prompt_text = prompt.read_text() if prompt and prompt.exists() else None |
| 89 | + generate_descriptions(doc_gen.snippets, prompt_text) |
| 90 | + |
| 91 | + |
| 92 | +if __name__ == "__main__": |
| 93 | + parser = argparse.ArgumentParser( |
| 94 | + description="Generate new titles and descriptions for DocGen snippets" |
| 95 | + ) |
| 96 | + parser.add_argument( |
| 97 | + "--doc-gen-root", required=True, help="Path to DocGen ready project" |
| 98 | + ) |
| 99 | + parser.add_argument( |
| 100 | + "--prompt", |
| 101 | + help="Path to an additional prompt to be used for refining the output", |
| 102 | + ) |
| 103 | + args = parser.parse_args() |
| 104 | + |
| 105 | + doc_gen_root = Path(args.doc_gen_root) |
| 106 | + prompt = Path(args.prompt) if args.prompt else None |
| 107 | + main(doc_gen_root, prompt) |
0 commit comments