Skip to content

Instantly share code, notes, and snippets.

@driukova
Created January 30, 2025 19:45
Show Gist options
  • Select an option

  • Save driukova/77c1d6b83264ee6020125017c85ce964 to your computer and use it in GitHub Desktop.

Select an option

Save driukova/77c1d6b83264ee6020125017c85ce964 to your computer and use it in GitHub Desktop.
API_docs_user_simulation_FOSDEM2025.ipynb
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/driukova/77c1d6b83264ee6020125017c85ce964/api_docs_user_simulation_fosdem2025.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8u3rkoUtAoPj"
},
"outputs": [],
"source": [
"%pip install cbor2==5.6.4\n",
"%pip install attrs==23.2.0\n",
"\n",
"# Make sure to install any libraries you need for your integration.\n",
"# For example:\n",
"# %pip install openai==0.27.8"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eQEKuJPq9GPd"
},
"outputs": [],
"source": [
"# import openai\n",
"import IPython.display\n",
"import json\n",
"\n",
"# Set the API key\n",
"# openai.api_key = \"YOUR_OPENAI_API_KEY\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"id": "IjxZbNvD9Or8"
},
"outputs": [],
"source": [
"# Load OpenAPI Specification\n",
"with open('/content/sample_data/petstore.json') as f:\n",
" openapi_spec = json.load(f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jQmyzM01R386"
},
"outputs": [],
"source": [
"# Extract global information\n",
"global_info = {\n",
" 'servers': openapi_spec.get('servers', []),\n",
" 'components': openapi_spec.get('components', {}),\n",
" 'security': openapi_spec.get('security', [])\n",
"}\n",
"\n",
"# Using the first server from the servers list\n",
"if global_info['servers']:\n",
" base_url = global_info['servers'][0].get('url', '')\n",
"else:\n",
" base_url = ''\n",
"\n",
"# Extract schema information from components\n",
"schemas = global_info['components'].get('schemas', {})\n",
"schemas_info_str = json.dumps(schemas, indent=2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dZaZNcWiEUR7"
},
"outputs": [],
"source": [
"# Function to recursively collect schemas from parameters and responses\n",
"def collect_schemas(details, schemas):\n",
" if 'parameters' in details:\n",
" for param in details['parameters']:\n",
" if 'schema' in param:\n",
" schemas[param['name']] = param['schema']\n",
" if 'responses' in details:\n",
" for response, resp_details in details['responses'].items():\n",
" if 'content' in resp_details:\n",
" for content_type, content_details in resp_details['content'].items():\n",
" if 'schema' in content_details:\n",
" if '$ref' in content_details['schema']:\n",
" ref_path = content_details['schema']['$ref']\n",
" ref_name = ref_path.split('/')[-1]\n",
" schemas[ref_name] = ref_path\n",
" else:\n",
" schemas[f\"{response}_{content_type}_schema\"] = content_details['schema']\n",
" return schemas"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "2hR82Mfm9Q0R"
},
"outputs": [],
"source": [
"# Extract endpoint information\n",
"endpoints_info = []\n",
"\n",
"for path, methods in openapi_spec.get('paths', {}).items():\n",
" for method, details in methods.items():\n",
" schema_details = collect_schemas(details, schemas.copy())\n",
" endpoint = {\n",
" 'path': path,\n",
" 'method': method.upper(),\n",
" 'full_url': f\"{base_url}{path}\",\n",
" 'summary': details.get('summary', ''),\n",
" 'description': details.get('description', details.get('operationId', '')),\n",
" 'schemas': schema_details,\n",
" }\n",
" endpoints_info.append(endpoint)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gGWZMWbeevOg"
},
"outputs": [],
"source": [
"print(endpoints_info) # Debugging step"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "dfW9pFm39VNv"
},
"outputs": [],
"source": [
"# Function to generate questions with OpenAI\n",
"def generate_questions_openai(context):\n",
" messages = [\n",
" {\n",
" \"role\": \"system\",\n",
" \"content\": \"You are a helpful assistant.\"\n",
" },\n",
" {\n",
" \"role\": \"user\",\n",
" \"content\": (\n",
" \"Act as a developer who uses the API documentation to understand how to implement, interact with, and integrate the API into their own applications or systems. Analyze the following OpenAPI 3.0 specification and make a list of potential questions a developer might have. Then check these questions against the provided specification again to ensure that they are not already answered. Concentrate on practical questions, not impossible or philosophical ones. Provide as output only a list of questions that are not answered within the specification, considering aspects such as usage, authentication, error handling and edge cases.\\n\\n\"\n",
" f\"{context}\"\n",
" )\n",
" }\n",
" ]\n",
"\n",
" response = openai.ChatCompletion.create(\n",
" model=\"gpt-3.5-turbo\",\n",
" messages=messages\n",
" )\n",
"\n",
" generated_text = response[\"choices\"][0][\"message\"][\"content\"]\n",
" questions = generated_text.strip().split(\"\\n\")\n",
" return [q.strip() for q in questions if q.strip()]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NEdIY8v1BMEn"
},
"outputs": [],
"source": [
"# Generate questions for each endpoint\n",
"questions_per_endpoint = {}\n",
"\n",
"# Convert global info to a string summary for inclusion in context\n",
"global_info_str = json.dumps(global_info, indent=2)\n",
"\n",
"for endpoint in endpoints_info:\n",
" # Convert schemas info to a string summary for inclusion in context\n",
" schemas_info_str = json.dumps(endpoint['schemas'], indent=2)\n",
"\n",
" context = f\"Endpoint: {endpoint['full_url']} [{endpoint['method']}]\\n\"\n",
" context += f\"Summary: {endpoint['summary']}\\n\"\n",
" context += f\"Description: {endpoint['description']}\\n\"\n",
" context += f\"Global Information: {global_info_str}\\n\"\n",
" context += f\"Schema Information: {schemas_info_str}\\n\"\n",
"\n",
" if context.strip():\n",
" questions = generate_questions_grazie(context)\n",
" questions_per_endpoint[endpoint['path']] = {\n",
" 'method': endpoint['method'],\n",
" 'full_url': endpoint['full_url'],\n",
" 'questions': questions\n",
" }"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tg5FmR4V9d-H"
},
"outputs": [],
"source": [
"print(questions_per_endpoint) # Debugging step to ensure it contains data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UL9Qi32H667T"
},
"outputs": [],
"source": [
"# Summary Report\n",
"for path, data in questions_per_endpoint.items():\n",
" display_content = f\"Endpoint: {path} [{data['method']}] - Full URL: {data['full_url']}\\n\"\n",
" display_content += \"Unanswered Questions:\\n\"\n",
" for question in data['questions']:\n",
" display_content += f\" - {question}\\n\"\n",
" display_content += \"\\n\" + \"-\"*40 + \"\\n\"\n",
" IPython.display.display(IPython.display.Markdown(display_content))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "khiKno4wFfcg"
},
"outputs": [],
"source": []
}
],
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment