Trích xuất dữ liệu có cấu trúc bằng cách gọi hàm

Xem trên AI của Google Chạy trong Google Colab Xem nguồn trên GitHub

Trong hướng dẫn này, bạn sẽ tìm hiểu một ví dụ về trích xuất dữ liệu có cấu trúc, sử dụng API Gemini để trích xuất danh sách nhân vật, mối quan hệ, sự vật và địa điểm trong một câu chuyện.

Thiết lập

pip install -U -q google-generativeai
import pathlib
import textwrap

import google.generativeai as genai
import google.ai.generativelanguage as glm


from IPython.display import display
from IPython.display import Markdown

from google.api_core import retry

def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))

Sau khi bạn có khoá API, hãy truyền khoá đó vào SDK. Bạn có thể làm điều này theo hai cách:

  • Đặt khoá vào biến môi trường GOOGLE_API_KEY (SDK sẽ tự động nhận khoá từ đó).
  • Truyền khoá đến genai.configure(api_key=...)
try:
    # Used to securely store your API key
    from google.colab import userdata

    # Or use `os.getenv('API_KEY')` to fetch an environment variable.
    GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')
except ImportError:
    import os
    GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']

genai.configure(api_key=GOOGLE_API_KEY)

Tác vụ mẫu

Đối với hướng dẫn này, bạn sẽ trích xuất các thực thể từ các câu chuyện bằng ngôn ngữ tự nhiên. Ví dụ: dưới đây là một câu chuyện do Gemini viết.

new_story = False

if new_story:
  model = genai.GenerativeModel(model_name='models/gemini-1.5-pro-latest')

  response = model.generate_content("""
      Write a long story about a girl with magic backpack, her family, and at
      least one other charater. Make sure everyone has names. Don't forget to
      describe the contents of the backpack, and where everyone and everything
      starts and ends up.""", request_options={'retry': retry.Retry()})
  story = response.text
  print(response.candidates[0].citation_metadata)
else:
  story = """In the quaint town of Willow Creek, nestled amidst rolling hills and whispering willows, resided a young girl named Anya. As she stepped out of the creaky wooden door of her modest cottage, her heart skipped a beat with excitement and anticipation. Today was her first day of school, and she couldn't wait to show off her prized possession - a magical backpack.\n\nHanded down to her from her grandmother, the backpack was no ordinary satchel. Its soft, emerald-green fabric shimmered with an ethereal glow, and its leather straps held secrets that only Anya knew. Within its capacious interior lay an enchanted world, filled with wonders that would ignite her imagination and change her life forever.\n\nAnya's parents, kind-hearted Elise and wise-bearded Edward, bid her farewell with warm embraces. "Remember, my dear," whispered her mother, "use your magic wisely and for good." Her father added, "Always seek knowledge, and let the backpack be your trusted companion."\n\nWith a skip in her step, Anya set off towards the town's only schoolhouse. On her way, she passed her best friend, Samuel, a curious and adventurous boy with a mischievous grin. "Hey, Anya," he called out. "Can I see your backpack?"\n\nAnya hesitated for a moment before unzipping the flap and revealing its contents. Samuel's eyes widened in amazement as he peered inside. There, nestled amidst pencils and notebooks, were a shimmering sword, a book of ancient spells, a tiny compass that always pointed north, and a magical key that could open any lock.\n\nTogether, they marveled at the backpack's wonders, promising to keep its secrets safe. As they approached the schoolhouse, Anya noticed a group of older children huddled together, their faces etched with fear. Curiosity getting the better of her, she cautiously approached.\n\n"What's wrong?" she asked.\n\nA tall, lanky boy stepped forward. "There's a monster in the forest," he stammered. "It's been terrorizing the town, attacking animals and even people."\n\nAnya's heart sank. The town of Willow Creek was small and peaceful, and the thought of a monster brought a shiver down her spine. She knew she had to do something to protect her family and friends.\n\nWithout a moment's hesitation, Anya opened her backpack and retrieved the shimmering sword. With a determined gleam in her eye, she turned to her terrified peers. "Don't worry," she said, her voice steady. "I'll take care of it."\n\nWith Samuel close behind her, Anya ventured into the shadowy depths of the forest. The trees seemed to whisper secrets as she passed, and the undergrowth rustled with unseen creatures. As they walked deeper into the forest, the air grew heavy and the ground beneath their feet trembled.\n\nSuddenly, they came to a clearing, and there before their eyes was the monster - a massive beast with sharp teeth, glowing red eyes, and claws that could crush a human with ease. The creature roared, a thunderous sound that shook the forest to its core.\n\nFear surged through Anya, but she refused to let it consume her. She drew the sword from its sheath and charged towards the monster. The blade shimmered in the sunlight, and as it struck the beast's hide, a blinding light erupted, enveloping everything in its radiance.\n\nWhen the light faded, the monster was gone, and in its place was a pile of shattered crystals. Anya had defeated the creature with the magic of her backpack, proving that even the smallest of objects could hold the greatest of powers.\n\nAs she and Samuel returned to the town, they were greeted as heroes. The people of Willow Creek rejoiced, and the legend of Anya, the girl with the magic backpack, was passed down through generations. And so, Anya continued her adventures, using the backpack's wonders to make the world a better place, one magical step at a time."""
to_markdown(story)

Tại thị trấn độc đáo Willow Creek, nép mình giữa những ngọn đồi thoai thoải và những hàng liễu rì rào, một cô bé tên là Anya sinh sống. Khi bước ra khỏi cánh cửa gỗ cằn cỗi của ngôi nhà nhỏ đơn giản của mình, trái tim cô nhảy lên nhịp đập đầy phấn khích và mong chờ. Hôm nay là ngày đầu tiên cô đi học, và cô rất háo hức khoe món đồ quý giá của mình – một chiếc ba lô kỳ diệu.

Được bà nội trao tặng cho cô, chiếc ba lô đó không phải là chiếc túi thông thường. Vải mềm mại màu xanh ngọc lục bảo của nó lấp lánh ánh sáng êm dịu, và dây da giữ bí mật mà chỉ Anya mới biết. Bên trong tiềm ẩn của nó là một thế giới mê hoặc, chứa đầy những điều kỳ diệu có thể khơi dậy trí tưởng tượng của cô và thay đổi cuộc đời cô mãi mãi.

Cha mẹ của Anya, Elise tốt bụng và Edward thông thái, đã tạm biệt cô bằng những cái ôm ấm áp. "Hãy nhớ con ơi", mẹ cô thì thầm, "hãy dùng phép thuật của con một cách khôn ngoan và vì điều tốt đẹp". Cha cô nói thêm: "Hãy luôn tìm kiếm kiến thức và hãy để chiếc ba lô trở thành người bạn đồng hành đáng tin cậy của con".

Sau khi bỏ qua bước chân, Anya khởi hành đến ngôi trường duy nhất của thành phố. Trên đường đi, cô ngang qua người bạn thân nhất của mình là Samuel, một cậu bé tò mò và thích phiêu lưu với nụ cười tinh nghịch. Cậu bé cất tiếng gọi "Hey Anya". "Tôi có thể xem ba lô của bạn không?"

Anya do dự trong giây lát trước khi mở khoá nắp và tiết lộ bên trong. Mắt Samuel mở rộng vì kinh ngạc khi anh nhìn vào bên trong. Ở đó, nép mình giữa những cây bút chì và quyển sổ tay, là một thanh kiếm sáng lung linh, quyển sách thần chú cổ xưa, một chiếc la bàn nhỏ luôn hướng về phía Bắc và một chiếc chìa khoá thần kỳ có thể mở bất kỳ ổ khoá nào.

Họ cùng nhau ngạc nhiên trước những điều kỳ diệu của chiếc ba lô, hứa hẹn sẽ giữ an toàn những bí mật của chiếc ba lô. Khi đến gần trường, Anya thấy một nhóm đứa trẻ lớn tuổi túm tụ với nhau, trên mặt đều khắc nét sợ hãi. Vì tò mò muốn thể hiện sự tò mò, cô càng thận trọng tiếp cận.

"Có chuyện gì vậy?" cô hỏi.

Một cậu bé cao lớn, gầy gò bước về phía trước. "Có một con quái vật trong rừng", anh ta lắp ráp. "Đó là hành vi khủng bố thành phố, tấn công động vật và thậm chí cả con người."

Trái tim của Anya chìm xuống. Thị trấn Willow Creek rất nhỏ bé và yên bình. Ý tưởng về quái vật đã khiến xương sống của cô rét buốt. Cô biết mình phải làm gì đó để bảo vệ gia đình và bạn bè.

Không chút do dự, Anya mở ba lô của mình và rút lại thanh kiếm sáng lung linh. Với ánh sáng lấp lánh trong mắt, cô nhìn vào những người đồng trang lứa đang sợ hãi. "Đừng lo", cô nói, giọng ổn định. "Tôi sẽ lo việc này."

Khi Samuel ở gần phía sau, Anya mạo hiểm đi vào những chiều sâu u ám của khu rừng. Những cái cây như thì thầm những bí mật khi cô đi qua, và những đám cây rình mò xung quanh những sinh vật lạ lẫm. Khi họ tiến sâu hơn vào khu rừng, không khí trở nên nặng nề và mặt đất dưới chân họ rung chuyển.

Đột nhiên, họ đi đến một bãi cỏ, trước mắt họ là con quái vật – một con quái vật to lớn với hàm răng sắc nhọn, đôi mắt sáng rực màu đỏ và móng vuốt có thể dễ dàng đè nén con người. Sinh vật này gầm gừ, một âm thanh như sấm sét làm rung chuyển khu rừng vào cốt lõi.

Anya càng sợ hãi, nhưng cô không muốn để cơ thể mình ăn thịt. Cô rút thanh kiếm ra khỏi vỏ và lao về phía con quái vật. Lưỡi kiếm toả sáng dưới ánh sáng mặt trời và khi nó đánh vào da con quái vật, một ánh sáng chói loá phun ra, bao phủ mọi thứ trong ánh sáng rực rỡ của nó.

Khi ánh sáng mờ dần, con quái vật đã biến mất và thay vào đó là một đống tinh thể bị vỡ. Anya đã đánh bại sinh vật này bằng phép thuật trên chiếc ba lô của mình, chứng minh rằng ngay cả những vật thể nhỏ nhất cũng có thể nắm giữ sức mạnh lớn nhất.

Khi cô và Samuel trở về thị trấn, họ được chào đón như những anh hùng. Người dân ở Willow Creek rất vui mừng và truyền thuyết về Anya, cô gái mang chiếc ba lô thần kỳ, đã được truyền qua nhiều thế hệ. Vậy nên, Anya tiếp tục hành trình của mình bằng cách sử dụng những kỳ quan của chiếc ba lô để biến thế giới thành một nơi tốt đẹp hơn, từng bước đi kỳ diệu.

Sử dụng Ngôn ngữ tự nhiên

Mô hình ngôn ngữ lớn là một công cụ mạnh mẽ đa nhiệm. Thường thì bạn chỉ cần hỏi Song Tử cho những gì mình muốn và mọi thứ sẽ ổn.

Có một vài điều cần chú ý khi tạo cấu trúc dữ liệu theo cách này:

  • Đôi khi, quá trình phân tích cú pháp không thành công.
  • Không thể thực thi nghiêm ngặt giản đồ này.

Bạn sẽ giải quyết những vấn đề đó trong phần tiếp theo. Trước tiên, hãy thử một câu lệnh đơn giản bằng ngôn ngữ tự nhiên với giản đồ được viết dưới dạng văn bản. Tính năng này chưa được tối ưu hoá:

model = model = model = genai.GenerativeModel(
    model_name='models/gemini-1.5-pro-latest')

response = model.generate_content(
  textwrap.dedent("""\
    Please return JSON describing the the people, places, things and relationships from this story using the following schema:

    {"people": list[PERSON], "places":list[PLACE], "things":list[THING], "relationships": list[RELATIONSHIP]}

    PERSON = {"name": str, "description": str, "start_place_name": str, "end_place_name": str}
    PLACE = {"name": str, "description": str}
    THING = {"name": str, "description": str, "start_place_name": str, "end_place_name": str}
    RELATIONSHIP = {"person_1_name": str, "person_2_name": str, "relationship": str}

    All fields are required.

    Important: Only return a single piece of valid JSON text.

    Here is the story:

    """) + story,
  generation_config={'response_mime_type':'application/json'}
)
response.text
'{"people": [\n    {\n        "name": "Anya",\n        "description": "A young girl who lives in the town of Willow Creek with her parents, Elise and Edward. She possesses a magical backpack that was handed down to her from her grandmother.",\n        "start_place_name": "Willow Creek",\n        "end_place_name": "Willow Creek"\n    },\n    {\n        "name": "Elise",\n        "description": "Anya\'s kind-hearted mother",\n        "start_place_name": "Willow Creek",\n        "end_place_name": "Willow Creek"\n    },\n    {\n        "name": "Edward",\n        "description": "Anya\'s wise-bearded father",\n        "start_place_name": "Willow Creek",\n        "end_place_name": "Willow Creek"\n    },\n    {\n        "name": "Samuel",\n        "description": "Anya\'s best friend, a curious and adventurous boy with a mischievous grin.",\n        "start_place_name": "Willow Creek",\n        "end_place_name": "Willow Creek"\n    },\n    {\n        "name": "Monster",\n        "description": "A massive beast with sharp teeth, glowing red eyes, and claws that could crush a human with ease.",\n        "start_place_name": "Forest",\n        "end_place_name": "Forest"\n    }\n], "places": [\n    {\n        "name": "Willow Creek",\n        "description": "A quaint town nestled amidst rolling hills and whispering willows."\n    },\n    {\n        "name": "Forest",\n        "description": "A shadowy place with rustling undergrowth and whispering trees."\n    },\n    {\n        "name": "Schoolhouse",\n        "description": "The only school in the town of Willow Creek."\n    },\n    {\n        "name": "Anya\'s home",\n        "description": "A modest cottage with a creaky wooden door."\n    }\n], "things": [\n    {\n        "name": "Magic backpack",\n        "description": "A magical backpack that was handed down to Anya from her grandmother. Its soft, emerald-green fabric shimmered with an ethereal glow, and its leather straps held secrets that only Anya knew.",\n        "start_place_name": "Anya\'s home",\n        "end_place_name": "Forest"\n    },\n    {\n        "name": "Shimmering sword",\n        "description": "A sword that shimmered in the sunlight and could strike with blinding light.",\n        "start_place_name": "Magic backpack",\n        "end_place_name": "Forest"\n    },\n    {\n        "name": "Book of ancient spells",\n        "description": "A book that contained ancient spells.",\n        "start_place_name": "Magic backpack",\n        "end_place_name": "Forest"\n    },\n    {\n        "name": "Tiny compass",\n        "description": "A compass that always pointed north.",\n        "start_place_name": "Magic backpack",\n        "end_place_name": "Forest"\n    },\n    {\n        "name": "Magical key",\n        "description": "A key that could open any lock.",\n        "start_place_name": "Magic backpack",\n        "end_place_name": "Forest"\n    },\n    {\n        "name": "Shattered crystals",\n        "description": "The remains of the monster after it was defeated by Anya\'s magic backpack.",\n        "start_place_name": "Forest",\n        "end_place_name": "Forest"\n    }\n], "relationships": [\n    {\n        "person_1_name": "Anya",\n        "person_2_name": "Elise",\n        "relationship": "mother-daughter"\n    },\n    {\n        "person_1_name": "Anya",\n        "person_2_name": "Edward",\n        "relationship": "father-daughter"\n    },\n    {\n        "person_1_name": "Anya",\n        "person_2_name": "Samuel",\n        "relationship": "best friends"\n    }\n]}'

Thao tác này trả về một chuỗi json. Hãy thử phân tích cú pháp:

import json

print(json.dumps(json.loads(response.text), indent=4))
{
    "people": [
        {
            "name": "Anya",
            "description": "A young girl who lives in the town of Willow Creek with her parents, Elise and Edward. She possesses a magical backpack that was handed down to her from her grandmother.",
            "start_place_name": "Willow Creek",
            "end_place_name": "Willow Creek"
        },
        {
            "name": "Elise",
            "description": "Anya's kind-hearted mother",
            "start_place_name": "Willow Creek",
            "end_place_name": "Willow Creek"
        },
        {
            "name": "Edward",
            "description": "Anya's wise-bearded father",
            "start_place_name": "Willow Creek",
            "end_place_name": "Willow Creek"
        },
        {
            "name": "Samuel",
            "description": "Anya's best friend, a curious and adventurous boy with a mischievous grin.",
            "start_place_name": "Willow Creek",
            "end_place_name": "Willow Creek"
        },
        {
            "name": "Monster",
            "description": "A massive beast with sharp teeth, glowing red eyes, and claws that could crush a human with ease.",
            "start_place_name": "Forest",
            "end_place_name": "Forest"
        }
    ],
    "places": [
        {
            "name": "Willow Creek",
            "description": "A quaint town nestled amidst rolling hills and whispering willows."
        },
        {
            "name": "Forest",
            "description": "A shadowy place with rustling undergrowth and whispering trees."
        },
        {
            "name": "Schoolhouse",
            "description": "The only school in the town of Willow Creek."
        },
        {
            "name": "Anya's home",
            "description": "A modest cottage with a creaky wooden door."
        }
    ],
    "things": [
        {
            "name": "Magic backpack",
            "description": "A magical backpack that was handed down to Anya from her grandmother. Its soft, emerald-green fabric shimmered with an ethereal glow, and its leather straps held secrets that only Anya knew.",
            "start_place_name": "Anya's home",
            "end_place_name": "Forest"
        },
        {
            "name": "Shimmering sword",
            "description": "A sword that shimmered in the sunlight and could strike with blinding light.",
            "start_place_name": "Magic backpack",
            "end_place_name": "Forest"
        },
        {
            "name": "Book of ancient spells",
            "description": "A book that contained ancient spells.",
            "start_place_name": "Magic backpack",
            "end_place_name": "Forest"
        },
        {
            "name": "Tiny compass",
            "description": "A compass that always pointed north.",
            "start_place_name": "Magic backpack",
            "end_place_name": "Forest"
        },
        {
            "name": "Magical key",
            "description": "A key that could open any lock.",
            "start_place_name": "Magic backpack",
            "end_place_name": "Forest"
        },
        {
            "name": "Shattered crystals",
            "description": "The remains of the monster after it was defeated by Anya's magic backpack.",
            "start_place_name": "Forest",
            "end_place_name": "Forest"
        }
    ],
    "relationships": [
        {
            "person_1_name": "Anya",
            "person_2_name": "Elise",
            "relationship": "mother-daughter"
        },
        {
            "person_1_name": "Anya",
            "person_2_name": "Edward",
            "relationship": "father-daughter"
        },
        {
            "person_1_name": "Anya",
            "person_2_name": "Samuel",
            "relationship": "best friends"
        }
    ]
}

Việc này tương đối đơn giản và thường hiệu quả, nhưng bạn có thể thực hiện việc này nghiêm ngặt/mạnh hơn bằng cách xác định giản đồ bằng tính năng gọi hàm của API.

Dùng lệnh gọi hàm

Nếu bạn chưa xem qua hướng dẫn Kiến thức cơ bản về tính năng gọi hàm, hãy nhớ thực hiện việc đó trước.

Với hàm gọi hàm và các tham số của hàm đó được mô tả cho API dưới dạng glm.FunctionDeclaration. Trong các trường hợp cơ bản, SDK có thể tạo FunctionDeclaration từ hàm và chú thích của hàm đó. SDK hiện không xử lý nội dung mô tả về các tham số OBJECT (dict) lồng nhau. Vì vậy, ngay bây giờ, bạn cần phải xác định rõ các giá trị này.

Xác định giản đồ

Bắt đầu bằng cách xác định person làm đối tượng với các trường chuỗi name, description, start_place_name, end_place_name.

person = glm.Schema(
    type = glm.Type.OBJECT,
    properties = {
        'name':  glm.Schema(type=glm.Type.STRING),
        'description':  glm.Schema(type=glm.Type.STRING),
        'start_place_name': glm.Schema(type=glm.Type.STRING),
        'end_place_name': glm.Schema(type=glm.Type.STRING)
    },
    required=['name', 'description', 'start_place_name', 'end_place_name']
)

Sau đó, hãy xác định mọi người dưới dạng ARRAY của đối tượng person:

people = glm.Schema(
    type=glm.Type.ARRAY,
    items=person
)

Sau đó, hãy thực hiện tương tự cho từng thực thể bạn đang cố gắng trích xuất:

place = glm.Schema(
    type = glm.Type.OBJECT,
    properties = {
        'name':  glm.Schema(type=glm.Type.STRING),
        'description':  glm.Schema(type=glm.Type.STRING),
    }
)

places = glm.Schema(
    type=glm.Type.ARRAY,
    items=place
)
thing = glm.Schema(
  type = glm.Type.OBJECT,
  properties = {
      'name':  glm.Schema(type=glm.Type.STRING),
      'description':  glm.Schema(type=glm.Type.STRING),
  }
)

things = glm.Schema(
    type=glm.Type.ARRAY,
    items=thing
)
relationship = glm.Schema(
    type = glm.Type.OBJECT,
    properties = {
        'person_1_name':  glm.Schema(type=glm.Type.STRING),
        'person_2_name':  glm.Schema(type=glm.Type.STRING),
        'relationship':  glm.Schema(type=glm.Type.STRING),
    }
)

relationships = glm.Schema(
    type=glm.Type.ARRAY,
    items=relationship
)

Giờ hãy tạo FunctionDeclaration:

add_to_database = glm.FunctionDeclaration(
    name="add_to_database",
    description=textwrap.dedent("""\
        Adds entities to the database.
        """),
    parameters=glm.Schema(
        type=glm.Type.OBJECT,
        properties = {
            'people': people,
            'places': places,
            'things': things,
            'relationships': relationships
        }
    )
)

Gọi API

Như bạn đã thấy trong phần Kiến thức cơ bản về lệnh gọi hàm, giờ đây bạn có thể truyền FunctionDeclaration này vào đối số tools của hàm khởi tạo genai.GenerativeModel (hàm khởi tạo cũng sẽ chấp nhận cách biểu diễn JSON tương đương của phần khai báo hàm):

model = model = genai.GenerativeModel(
    model_name='models/gemini-1.5-pro-latest',
    tools = [add_to_database])

Mỗi khi bạn gọi API, SDK sẽ gửi các công cụ cùng với lời nhắc của bạn và mô hình sẽ gọi hàm mà bạn đã xác định:

result = model.generate_content(f"""
Please add the people, places, things, and relationships from this story to the database:

{story}
""",
# Force a function call
tool_config={'function_calling_config':'ANY'})

Hiện không có văn bản nào để phân tích. Kết quả chính là một cấu trúc dữ liệu.

'text' in result.candidates[0].content.parts[0]
False
'function_call' in result.candidates[0].content.parts[0]
True
fc = result.candidates[0].content.parts[0].function_call
print(type(fc))
<class 'google.ai.generativelanguage_v1beta.types.content.FunctionCall'>

Lớp glm.FunctionCall dựa trên Vùng đệm giao thức Google, hãy chuyển đổi lớp này thành một đối tượng tương thích với JSON quen thuộc hơn:

print(json.dumps(type(fc).to_dict(fc), indent=4))
{
    "name": "add_to_database",
    "args": {
        "things": [
            {
                "name": "Magical Backpack",
                "description": "Anya's prized possession, the Magical Backpack, is no ordinary satchel. Its soft, emerald-green fabric shimmers with an ethereal glow, and its leather straps have secrets that only Anya knows. Within its capacious interior lay an enchanted world, filled with wonders that would ignite her imagination and change her life forever."
            },
            {
                "name": "Shimmering Sword",
                "description": "Among the wonders in Anya's Magical Backpack, lies a shimmering sword. With a determined gleam in her eye, she retrieved the shimmering sword and charged towards the monster."
            },
            {
                "description": "Residing within the Magical Backpack, the Book of Ancient Spells holds secrets untold.",
                "name": "Book of Ancient Spells"
            },
            {
                "description": "Tucked away in the Magical Backpack is a tiny compass that always points north.",
                "name": "Tiny Compass that Always Points North"
            },
            {
                "description": "Hidden within the Magical Backpack is a magical key that can open any lock.",
                "name": "Magical Key that Can Open Any Lock"
            }
        ],
        "relationships": [
            {
                "relationship": "Mother-Daughter",
                "person_1_name": "Anya",
                "person_2_name": "Elise"
            },
            {
                "person_2_name": "Edward",
                "relationship": "Father-Daughter",
                "person_1_name": "Anya"
            },
            {
                "person_2_name": "Samuel",
                "person_1_name": "Anya",
                "relationship": "Best Friends"
            }
        ],
        "people": [
            {
                "name": "Anya",
                "description": "Anya, the main character of the story, is a young girl with a magical backpack.",
                "start_place_name": "Willow Creek",
                "end_place_name": "Unknown"
            },
            {
                "name": "Elise",
                "description": "Anya's mother, Elise is a kind-hearted woman.",
                "end_place_name": "Unknown",
                "start_place_name": "Willow Creek"
            },
            {
                "start_place_name": "Willow Creek",
                "end_place_name": "Unknown",
                "name": "Edward",
                "description": "Anya's father, Edward is a wise-bearded man."
            },
            {
                "end_place_name": "Unknown",
                "start_place_name": "Willow Creek",
                "description": "Anya's best friend, Samuel is a curious and adventurous boy with a mischievous grin.",
                "name": "Samuel"
            }
        ],
        "places": [
            {
                "description": "The quaint town of Willow Creek is nestled amidst rolling hills and whispering willows.",
                "name": "Willow Creek"
            },
            {
                "description": "The town's only schoolhouse.",
                "name": "Schoolhouse"
            },
            {
                "description": "A shadowy place filled with secrets and dangers, the Forest is home to a terrifying monster.",
                "name": "Forest"
            }
        ]
    }
}

Kết luận

Mặc dù API có thể xử lý các sự cố trích xuất dữ liệu có cấu trúc bằng phương thức nhập và xuất văn bản thuần tuý, nhưng việc sử dụng phương thức gọi hàm có thể đáng tin cậy hơn vì cho phép bạn xác định một giản đồ nghiêm ngặt và loại bỏ bước phân tích cú pháp dễ xảy ra lỗi.