Skip to content

docs: refactor quickstart#8566

Closed
mendonk wants to merge 18 commits into
mainfrom
docs-refactor-quickstart
Closed

docs: refactor quickstart#8566
mendonk wants to merge 18 commits into
mainfrom
docs-refactor-quickstart

Conversation

@mendonk
Copy link
Copy Markdown
Collaborator

@mendonk mendonk commented Jun 16, 2025

Closed to manage dependencies in another PR. See #8582

Preview build
Rewrite quickstart to "Run Simple agent in Langflow IDE -> expose as API endpoint -> run it with a python or js application".

TODO:

  1. More info on output schema

@mendonk mendonk self-assigned this Jun 16, 2025
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 16, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 16, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Several new example scripts in Python, JavaScript, and shell are introduced to demonstrate interacting with a local API endpoint for chat-based queries. The quickstart documentation is extensively revised to focus on running and serving flows via the API, providing updated code samples, and introducing runtime overrides. A new package.json is also added.

Changes

File(s) Change Summary
docs/docs/Get-Started/examples/get-started.js, get-started.py, docs/docs/Get-Started/examples/get-started.py Added interactive terminal chat scripts in JavaScript and Python for querying a local API, handling user input, and commands.
docs/docs/Get-Started/examples/playground-default.js, docs/docs/Get-Started/examples/playground-default.py, docs/docs/Get-Started/examples/playground-default.sh Added standalone example scripts (JavaScript, Python, shell) for sending POST requests to the API with chat payloads.
docs/docs/Get-Started/get-started-quickstart.md Overhauled quickstart documentation to focus on running flows via API, removed RAG tutorial, added new code/API examples.
package.json Added new file specifying raw-loader dependency.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Script (Python/JS)
    participant API Server

    User->>Script (Python/JS): Enter question/command
    alt quit
        Script (Python/JS)->>User: Exit program
    else compare
        Script (Python/JS)->>User: Show previous answer
        User->>Script (Python/JS): Enter next question/command
    else normal question
        Script (Python/JS)->>API Server: POST /api/v1/run/{id} (question payload)
        API Server-->>Script (Python/JS): Response (chat answer)
        Script (Python/JS)->>User: Display answer
        User->>Script (Python/JS): Enter next question/command
    end
Loading

Suggested labels

documentation, size:M, lgtm

Suggested reviewers

  • KimberlyFields
✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch docs-refactor-quickstart
  • Post Copyable Unit Tests in Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mendonk mendonk requested a review from aimurphy June 16, 2025 22:57
@dosubot dosubot Bot added the documentation Improvements or additions to documentation label Jun 16, 2025
@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
@mendonk mendonk added the draft label Jun 16, 2025
@github-actions

This comment was marked as outdated.

@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (11)
get-started.py (2)

1-3: Remove unused import and add a short module docstring

json is never used and Ruff flags the missing docstring.

-import requests
-import json
+"""
+Minimal interactive example for chatting with a Langflow agent via REST.
+"""
+
+import requests

34-54: CLI loop: break/continue structure can be simplified

After break the following elif is redundant; also prefer using sys.exit() for clarity and add a newline at EOF.

-    if user_question.lower() == 'quit':
-        break
-    elif user_question.lower() == 'compare':
+    if user_question.lower() == "quit":
+        sys.exit(0)
+    if user_question.lower() == "compare":
docs/docs/Get-Started/examples/playground-default.sh (1)

1-8: Add shebang & quote the JSON payload cleanly

Shellcheck warns because no interpreter is specified. Also, multiline JSON with tab characters can be fragile; use a here-doc or compact one-liner.

+#!/usr/bin/env bash
+
+curl -sS -X POST "http://localhost:7860/api/v1/run/29deb764-af3f-4d7d-94a0-47491ed241d6?stream=false" \
+  -H "Content-Type: application/json" \
+  -d '{"output_type":"chat","input_type":"chat","input_value":"hello world!"}'
docs/docs/Get-Started/examples/playground-default.js (1)

8-19: Handle non-200 responses in fetch and make the example await-friendly

Beginners will copy this snippet verbatim; surfacing HTTP errors prevents silent failures.

-fetch('http://localhost:7860/api/v1/run/29deb764-af3f-4d7d-94a0-47491ed241d6', options)
-    .then(response => response.json())
-    .then(response => console.log(response))
-    .catch(err => console.error(err));
+fetch('http://localhost:7860/api/v1/run/29deb764-af3f-4d7d-94a0-47491ed241d6', options)
+  .then(async res => {
+    if (!res.ok) {
+      throw new Error(`HTTP ${res.status}: ${await res.text()}`);
+    }
+    return res.json();
+  })
+  .then(console.log)
+  .catch(console.error);
docs/docs/Get-Started/examples/playground-default.py (1)

25-28: Prefer logging over bare prints for example code

Using logging demonstrates best practices and lets users control verbosity.

-import requests.exceptions.RequestException as e:
-    print(f"Error making API request: {e}")
+import logging
+...
+except requests.exceptions.RequestException as exc:
+    logging.error("API request failed: %s", exc)
docs/docs/Get-Started/examples/get-started.js (1)

8-8: Make the endpoint configurable

Hard-coding the flow ID forces users to modify source code. Read from an env-var or CLI arg instead:

-const url = 'http://localhost:7860/api/v1/run/29deb764-af3f-4d7d-94a0-47491ed241d6';
+const url = process.env.LANGFLOW_RUN_URL ??
+  'http://localhost:7860/api/v1/run/29deb764-af3f-4d7d-94a0-47491ed241d6';
docs/docs/Get-Started/examples/get-started.py (3)

1-3: Remove unused import

json is never referenced.

-import json

38-40: Extraneous closing parenthesis in prompt text

The trailing ) sneaks into the printed message.

-print("\nAsk the agent anything, such as 'What is 15 * 7?' or 'What is the capital of France?')")
+print("\nAsk the agent anything, such as 'What is 15 * 7?' or 'What is the capital of France?'")

36-55: Simplify control flow & fix elif after break lint

After break the loop terminates, so elif is redundant; use if. Also align wording (“quit” vs “exit”) with docs for consistency.

-    if user_question.lower() == 'quit':
-        break
-    elif user_question.lower() == 'compare':
+    if user_question.lower() in ('quit', 'exit'):
+        break
+    if user_question.lower() == 'compare':
docs/docs/Get-Started/get-started-quickstart.md (2)

124-131: Replace hard tabs with spaces

Markdownlint flags hard tabs on these lines; they also break alignment in some renderers.

-	curl --request POST \
-	     --url 'http://localhost:7860/... \
-	     --header 'Content-Type: application/json' \
-	     --data '{ ... }'
+curl --request POST \
+     --url 'http://localhost:7860/... \
+     --header 'Content-Type: application/json' \
+     --data '{ ... }'

334-392: Duplicate example code—risk of drift

The Python & JS chat loops are copy-pasted both here and in examples/. When the sample scripts evolve the docs will silently rot. Prefer:

  1. Keeping the authoritative code only in examples/.
  2. Importing it via raw-loader as done elsewhere (getStartedPython, getStartedJavascript).

This eliminates duplication and guarantees the docs always display runnable code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b773513 and 9689d3a.

⛔ Files ignored due to path filters (4)
  • docs/static/img/quickstart-basic-prompt-no-connections.png is excluded by !**/*.png
  • docs/static/img/quickstart-simple-agent-playground.png is excluded by !**/*.png
  • docs/static/img/starter-flow-simple-agent.png is excluded by !**/*.png
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (8)
  • docs/docs/Get-Started/examples/get-started.js (1 hunks)
  • docs/docs/Get-Started/examples/get-started.py (1 hunks)
  • docs/docs/Get-Started/examples/playground-default.js (1 hunks)
  • docs/docs/Get-Started/examples/playground-default.py (1 hunks)
  • docs/docs/Get-Started/examples/playground-default.sh (1 hunks)
  • docs/docs/Get-Started/get-started-quickstart.md (1 hunks)
  • get-started.py (1 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
get-started.py (1)
docs/docs/Get-Started/examples/get-started.js (3)
  • url (8-8)
  • response (29-29)
  • message (33-33)
docs/docs/Get-Started/examples/playground-default.py (2)
docs/docs/Get-Started/examples/get-started.js (1)
  • url (8-8)
docs/docs/Get-Started/examples/playground-default.js (1)
  • payload (1-6)
docs/docs/Get-Started/examples/get-started.py (1)
docs/docs/Get-Started/examples/get-started.js (5)
  • url (8-8)
  • payload (14-18)
  • response (29-29)
  • data (30-30)
  • message (33-33)
🪛 Shellcheck (0.10.0)
docs/docs/Get-Started/examples/playground-default.sh

[error] 1-1: Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.

(SC2148)

🪛 Ruff (0.11.9)
get-started.py

1-1: Missing docstring in public module

(D100)


2-2: json imported but unused

Remove unused import: json

(F401)


6-6: Missing docstring in public function

(D103)


16-16: Blank line contains whitespace

Remove whitespace from blank line

(W293)


18-18: Blank line contains whitespace

Remove whitespace from blank line

(W293)


20-20: Probable use of requests call without timeout

(S113)


22-22: Blank line contains whitespace

Remove whitespace from blank line

(W293)


26-26: Consider moving this statement to an else block

(TRY300)


26-26: Unnecessary assignment to message before return statement

Remove unnecessary assignment

(RET504)


27-27: Blank line contains whitespace

Remove whitespace from blank line

(W293)


28-28: Do not catch blind exception: Exception

(BLE001)


29-29: Use explicit conversion flag

Replace with conversion flag

(RUF010)


36-36: print found

Remove print

(T201)


37-37: print found

Remove print

(T201)


39-39: Blank line contains whitespace

Remove whitespace from blank line

(W293)


40-40: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


42-42: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


44-44: print found

Remove print

(T201)


46-46: print found

Remove print

(T201)


48-48: Blank line contains whitespace

Remove whitespace from blank line

(W293)


51-51: print found

Remove print

(T201)


52-52: Blank line contains whitespace

Remove whitespace from blank line

(W293)


54-54: No newline at end of file

Add trailing newline

(W292)

docs/docs/Get-Started/examples/playground-default.py

1-1: File docs/docs/Get-Started/examples/playground-default.py is part of an implicit namespace package. Add an __init__.py.

(INP001)


1-1: Missing docstring in public module

(D100)


3-3: Line too long (124 > 120)

(E501)


19-19: Probable use of requests call without timeout

(S113)


23-23: print found

Remove print

(T201)


26-26: print found

Remove print

(T201)


28-28: print found

Remove print

(T201)


28-28: No newline at end of file

Add trailing newline

(W292)

docs/docs/Get-Started/examples/get-started.py

1-1: File docs/docs/Get-Started/examples/get-started.py is part of an implicit namespace package. Add an __init__.py.

(INP001)


1-1: Missing docstring in public module

(D100)


2-2: json imported but unused

Remove unused import: json

(F401)


6-6: Missing docstring in public function

(D103)


16-16: Probable use of requests call without timeout

(S113)


22-22: Consider moving this statement to an else block

(TRY300)


22-22: Unnecessary assignment to message before return statement

Remove unnecessary assignment

(RET504)


24-24: Do not catch blind exception: Exception

(BLE001)


25-25: Use explicit conversion flag

Replace with conversion flag

(RUF010)


27-27: Missing docstring in public function

(D103)


38-38: print found

Remove print

(T201)


39-39: print found

Remove print

(T201)


41-41: Blank line contains whitespace

Remove whitespace from blank line

(W293)


42-42: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


44-44: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


46-46: print found

Remove print

(T201)


48-48: print found

Remove print

(T201)


50-50: Blank line contains whitespace

Remove whitespace from blank line

(W293)


53-53: print found

Remove print

(T201)


53-53: Trailing whitespace

Remove trailing whitespace

(W291)

🪛 Pylint (3.3.7)
get-started.py

[refactor] 40-47: Unnecessary "elif" after "break", remove the leading "el" from "elif"

(R1723)

docs/docs/Get-Started/examples/get-started.py

[refactor] 42-49: Unnecessary "elif" after "break", remove the leading "el" from "elif"

(R1723)

🪛 LanguageTool
docs/docs/Get-Started/get-started-quickstart.md

[style] ~10-~10: Using many exclamation marks might seem excessive (in this case: 15 exclamation marks for a text that’s 4939 characters long)
Context: ...ock'; import getStartedJavascript from '!!raw-loader!./examples/get-started.js'; import getStartedPython from '!!raw-loader!./examples/get-started.py'; import playgroundJavascriptCode from '!!raw-loader!./examples/playground-default.js'; import playgroundPythonCode from '!!raw-loader!./examples/playground-default.py'; import playgroundCurlCode from '!!raw-loader!./examples/playground-default.sh'; Get ...

(EN_EXCESSIVE_EXCLAMATION)


[style] ~49-~49: Consider using an alternative to strengthen your wording.
Context: ...ate more flows within Langflow. If you want to learn how Langflow integrates into e...

(WANT_KEEN)

🪛 markdownlint-cli2 (0.17.2)
docs/docs/Get-Started/get-started-quickstart.md

128-128: Hard tabs
Column: 1

(MD010, no-hard-tabs)


129-129: Hard tabs
Column: 1

(MD010, no-hard-tabs)


130-130: Hard tabs
Column: 1

(MD010, no-hard-tabs)


131-131: Hard tabs
Column: 1

(MD010, no-hard-tabs)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: CI Success
  • GitHub Check: build-and-deploy
  • GitHub Check: Ruff Style Check (3.13)
  • GitHub Check: Run Ruff Check and Format
  • GitHub Check: Update Starter Projects
🔇 Additional comments (2)
package.json (1)

2-4: ```shell
#!/bin/bash

Locate webpack configuration files

echo "Webpack config files found:"
fd webpack.config.* -t f

echo

Search entire repo for raw-loader usage

echo "Occurrences of 'raw-loader' in codebase:"
rg -n "raw-loader" -C 3


</details>
<details>
<summary>docs/docs/Get-Started/examples/get-started.js (1)</summary>

`1-6`: **`fetch` is not available in Node < 18**

If users run the example with Node 16 they will hit `ReferenceError: fetch is not defined`. Add a comment or polyfill import (`node-fetch`) so the snippet works across LTS versions.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread get-started.py Outdated
Comment on lines +28 to +29
except Exception as e:
return f"Error: {str(e)}"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid catching bare Exception; surface stack-trace for debugging

Catching everything masks bugs such as KeyError above. Catch only the exceptions you can recover from (requests.RequestException, ValueError) and let the rest propagate or re-raise with context.

🧰 Tools
🪛 Ruff (0.11.9)

28-28: Do not catch blind exception: Exception

(BLE001)


29-29: Use explicit conversion flag

Replace with conversion flag

(RUF010)

🤖 Prompt for AI Agents
In get-started.py around lines 28 to 29, avoid catching the bare Exception as it
hides bugs and stack traces. Instead, catch only specific exceptions you expect
and can handle, such as requests.RequestException and ValueError. For other
exceptions, allow them to propagate or re-raise them with additional context to
preserve debugging information.

Comment thread get-started.py Outdated
Comment on lines +19 to +26
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()

# Get the response message
data = response.json()
message = data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]
return message
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle HTTP errors & malformed JSON explicitly

Blindly indexing deeply nested keys will raise KeyError on non-200 responses or schema changes.

-        response = requests.post(url, json=payload, headers=headers)
+        response = requests.post(url, json=payload, headers=headers, timeout=TIMEOUT)
         response.raise_for_status()
         
-        # Get the response message
-        data = response.json()
-        message = data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]
-        return message
+        data = response.json()
+        try:
+            return (
+                data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]
+            )
+        except (KeyError, IndexError, TypeError) as exc:
+            return f"Unexpected response schema: {exc!s}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
# Get the response message
data = response.json()
message = data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]
return message
try:
- response = requests.post(url, json=payload, headers=headers)
+ response = requests.post(url, json=payload, headers=headers, timeout=TIMEOUT)
response.raise_for_status()
- # Get the response message
- data = response.json()
- message = data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]
- return message
+ data = response.json()
+ try:
+ return (
+ data["outputs"][0]["outputs"][0]["outputs"]["message"]["message"]
+ )
+ except (KeyError, IndexError, TypeError) as exc:
+ return f"Unexpected response schema: {exc!s}"
🧰 Tools
🪛 Ruff (0.11.9)

20-20: Probable use of requests call without timeout

(S113)


22-22: Blank line contains whitespace

Remove whitespace from blank line

(W293)


26-26: Consider moving this statement to an else block

(TRY300)


26-26: Unnecessary assignment to message before return statement

Remove unnecessary assignment

(RET504)

🤖 Prompt for AI Agents
In get-started.py around lines 19 to 26, the code blindly indexes deeply nested
keys in the JSON response, which can cause KeyError if the HTTP response is not
200 or if the JSON schema changes. To fix this, explicitly handle HTTP errors by
catching exceptions from response.raise_for_status(), and safely access nested
JSON keys using methods like dict.get() with default values or try-except blocks
to catch KeyError or JSONDecodeError, ensuring the code gracefully handles
malformed or unexpected responses.

Comment thread get-started.py Outdated
Comment on lines +6 to +16
def ask_agent(question):
# Payload structure for Langflow API:
# - output_type: Specifies the type of output expected ("chat" for text responses)
# - input_type: Specifies the type of input being sent ("chat" for text questions)
# - input_value: The actual question or message to send to the agent
payload = {
"output_type": "chat", # Must be "chat" for text responses
"input_type": "chat", # Must be "chat" for text input
"input_value": question # Your question or message
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add type hints & timeout to network-facing helper

Providing types helps users copy-paste safely, and a timeout prevents the CLI from hanging forever.

-def ask_agent(question):
+from typing import Final
+
+TIMEOUT: Final = 10  # seconds
+
+def ask_agent(question: str) -> str:
@@
-    headers = {"Content-Type": "application/json"}
+    headers: dict[str, str] = {"Content-Type": "application/json"}

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.11.9)

6-6: Missing docstring in public function

(D103)


16-16: Blank line contains whitespace

Remove whitespace from blank line

(W293)

🤖 Prompt for AI Agents
In get-started.py around lines 6 to 16, the ask_agent function lacks type hints
and a timeout for network calls. Add appropriate type hints to the function
signature, specifying the input parameter and return type. Also, when making any
network requests inside the function, include a timeout parameter to prevent the
CLI from hanging indefinitely.

Comment on lines +17 to +23
try:
# Send API request
response = requests.request("POST", url, json=payload, headers=headers)
response.raise_for_status() # Raise exception for bad status codes

# Print response
print(response.text)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Specify timeout and log structured JSON instead of raw text

-    response = requests.request("POST", url, json=payload, headers=headers)
+    response = requests.post(url, json=payload, headers=headers, timeout=10)
@@
-    print(response.text)
+    print(response.json())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
# Send API request
response = requests.request("POST", url, json=payload, headers=headers)
response.raise_for_status() # Raise exception for bad status codes
# Print response
print(response.text)
try:
# Send API request
- response = requests.request("POST", url, json=payload, headers=headers)
+ response = requests.post(url, json=payload, headers=headers, timeout=10)
response.raise_for_status() # Raise exception for bad status codes
# Print response
- print(response.text)
+ print(response.json())
🧰 Tools
🪛 Ruff (0.11.9)

19-19: Probable use of requests call without timeout

(S113)


23-23: print found

Remove print

(T201)

🤖 Prompt for AI Agents
In docs/docs/Get-Started/examples/playground-default.py around lines 17 to 23,
the requests call lacks a timeout parameter and the response is printed as raw
text. Add a timeout argument to the requests.request call to avoid hanging
indefinitely, and parse the response as JSON to log it in a structured format
instead of printing raw text.

Comment on lines +32 to +34
// Extract the message from the nested response
const message = data.outputs[0].outputs[0].outputs.message.message;
return message;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Brittle deep-property access

data.outputs[0].outputs[0].outputs.message.message will explode on any schema drift. Wrap it with optional chaining or a helper:

-const message = data.outputs[0].outputs[0].outputs.message.message;
+const message =
+    data?.outputs?.[0]?.outputs?.[0]?.outputs?.message?.message ??
+    'Could not extract message from response';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Extract the message from the nested response
const message = data.outputs[0].outputs[0].outputs.message.message;
return message;
// Extract the message from the nested response
const message =
data?.outputs?.[0]?.outputs?.[0]?.outputs?.message?.message ??
'Could not extract message from response';
return message;
🤖 Prompt for AI Agents
In docs/docs/Get-Started/examples/get-started.js around lines 32 to 34, the code
accesses a deeply nested property with
data.outputs[0].outputs[0].outputs.message.message, which is brittle and can
cause runtime errors if any part of the path is undefined. Refactor this to use
optional chaining (?.) to safely access each nested property or implement a
helper function to safely retrieve the nested message, preventing crashes due to
schema changes.

Comment on lines +28 to +34
try {
const response = await fetch(url, options);
const data = await response.json();

// Extract the message from the nested response
const message = data.outputs[0].outputs[0].outputs.message.message;
return message;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle non-OK HTTP responses & provide clearer error messages

fetch() resolves even on 4xx/5xx. Trying to read data.outputs… on an error page will throw, but the catch will surface only TypeErrors that reach it. Check response.ok first and surface the server’s error body (if any) before JSON-parsing:

-        const response = await fetch(url, options);
-        const data = await response.json();
+        const response = await fetch(url, options);
+
+        if (!response.ok) {
+            const text = await response.text();
+            throw new Error(`HTTP ${response.status}: ${text}`);
+        }
+
+        const data = await response.json();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const response = await fetch(url, options);
const data = await response.json();
// Extract the message from the nested response
const message = data.outputs[0].outputs[0].outputs.message.message;
return message;
try {
const response = await fetch(url, options);
if (!response.ok) {
const text = await response.text();
throw new Error(`HTTP ${response.status}: ${text}`);
}
const data = await response.json();
// Extract the message from the nested response
const message = data.outputs[0].outputs[0].outputs.message.message;
return message;
🤖 Prompt for AI Agents
In docs/docs/Get-Started/examples/get-started.js around lines 28 to 34, the code
does not check if the HTTP response is successful before parsing JSON, which can
cause errors when the server returns 4xx or 5xx status codes. Add a check for
response.ok after the fetch call; if false, read and throw an error with the
server's error message or status text before attempting to parse the JSON. This
ensures clearer error handling and prevents accessing nested properties on error
responses.

Comment on lines +15 to +18
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add a timeout to the network call

A hung server will block the REPL indefinitely.

-        response = requests.post(url, json=payload, headers=headers)
+        response = requests.post(url, json=payload, headers=headers, timeout=30)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
try:
response = requests.post(url, json=payload, headers=headers, timeout=30)
response.raise_for_status()
🧰 Tools
🪛 Ruff (0.11.9)

16-16: Probable use of requests call without timeout

(S113)

🤖 Prompt for AI Agents
In docs/docs/Get-Started/examples/get-started.py around lines 15 to 18, the
requests.post call lacks a timeout parameter, which can cause the program to
hang indefinitely if the server does not respond. Add a timeout argument to the
requests.post call, specifying a reasonable number of seconds to wait before
raising a timeout exception, to prevent indefinite blocking.

Comment on lines +24 to +25
except Exception as e:
return f"Error: {str(e)}"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid blanket except Exception

Catching every exception masks programming errors (e.g. KeyError in the parsing logic). Catch the specific network & JSON exceptions instead:

-    except Exception as e:
-        return f"Error: {str(e)}"
+    except (requests.exceptions.RequestException, ValueError) as err:
+        return f"Request error: {err}"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
except Exception as e:
return f"Error: {str(e)}"
except (requests.exceptions.RequestException, ValueError) as err:
return f"Request error: {err}"
🧰 Tools
🪛 Ruff (0.11.9)

24-24: Do not catch blind exception: Exception

(BLE001)


25-25: Use explicit conversion flag

Replace with conversion flag

(RUF010)

🤖 Prompt for AI Agents
In docs/docs/Get-Started/examples/get-started.py around lines 24 to 25, replace
the broad 'except Exception' clause with specific exception handlers for
network-related errors and JSON parsing errors. Identify the exact exceptions
raised by the network requests and JSON operations (such as
requests.exceptions.RequestException and json.JSONDecodeError) and catch only
those to avoid masking other programming errors.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 16, 2025
@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Jun 16, 2025
@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jun 16, 2025

Build successful! ✅
Deploying docs draft.
Deploy successful! View draft

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 16, 2025
@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jun 16, 2025

Build successful! ✅
Deploying docs draft.
Deploy successful! View draft

@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jun 16, 2025

Build successful! ✅
Deploying docs draft.
Deploy successful! View draft

@github-actions
Copy link
Copy Markdown
Contributor

Build failure! ❌

@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 16, 2025
@mendonk
Copy link
Copy Markdown
Collaborator Author

mendonk commented Jun 17, 2025

Closing to manage dependencies in another PR

@mendonk mendonk closed this Jun 17, 2025
@mendonk mendonk deleted the docs-refactor-quickstart branch June 17, 2025 12:33
@github-actions github-actions Bot added documentation Improvements or additions to documentation and removed documentation Improvements or additions to documentation labels Jun 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation draft size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant