[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M698WFXH9WDGGWSXB1W66X5Z":3,"skill-same:01M698WFXH9WDGGWSXB1W66X5Z":106},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":45,"linkOnly":46,"markdownContent":47,"markdownBody":48,"frontMatter":49,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":55,"ownerHtmlUrl":56,"ownerBlogUrl":57,"ownerDescription":58,"updatedAt":59,"install":60,"resources":73},"01M698WFXH9WDGGWSXB1W66X5Z","langextract-usage",null,"How to use LangExtract to extract structured information from text. Use when writing code that calls lx.extract(), building extraction pipelines, defining examples, or troubleshooting alignment issues.","google\u002Flangextract","google","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1342004?v=4","01M698VYEFDM0VJBZDYYJ2T83S","Google","01M698WE0D9CJM711V3F1KMGQ9",39298,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000036","内容创作者","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],"langextract usage","writing","code","issues","extraction","examples","how","text","troubleshooting","extract","use","pipelines","alignment","structured","how to","information","2026-11-10 10:12:30",false,"---\nname: langextract-usage\ndescription: How to use LangExtract to extract structured information from text. Use when writing code that calls lx.extract(), building extraction pipelines, defining examples, or troubleshooting alignment issues.\n---\n\n# LangExtract Usage\n\nLangExtract extracts structured information from unstructured text using LLMs.\nThe main entry point is `lx.extract()`. Every extraction needs at least one\nexample and input text. `prompt_description` is optional but recommended.\n\n## Install\n\n```bash\npip install langextract\n\n# For OpenAI model support:\npip install langextract[openai]\n```\n\n## API keys\n\n```bash\n# Gemini (checks GEMINI_API_KEY then LANGEXTRACT_API_KEY)\nexport GEMINI_API_KEY=\"your_key\"\n\n# OpenAI (checks OPENAI_API_KEY then LANGEXTRACT_API_KEY)\nexport OPENAI_API_KEY=\"your_key\"\n\n# Ollama: no API key needed, just a running Ollama server\n```\n\nAuto-routing + env-default resolution is tuned for GPT-style model IDs\n(`gpt-4*`, `gpt-5*`, `gpt-6*`). For OpenAI-compatible endpoints or\nnon-GPT IDs, pass an explicit `ModelConfig` — see `references\u002Fproviders.md`.\n\n## Basic extraction\n\n```python\nimport langextract as lx\n\nexamples = [\n    lx.data.ExampleData(\n        text=\"Patient takes lisinopril 10mg daily for hypertension.\",\n        extractions=[\n            lx.data.Extraction(\n                extraction_class=\"medication\",\n                extraction_text=\"lisinopril\",\n                attributes={\"dose\": \"10mg\", \"frequency\": \"daily\"},\n            ),\n            lx.data.Extraction(\n                extraction_class=\"condition\",\n                extraction_text=\"hypertension\",\n                attributes={\"status\": \"active\"},\n            ),\n        ],\n    )\n]\n\nresult = lx.extract(\n    text_or_documents=\"Patient is prescribed metformin 500mg twice daily.\",\n    prompt_description=\"Extract medications and conditions with attributes.\",\n    examples=examples,\n    model_id=\"gemini-2.5-flash\",\n)\n\nfor e in result.extractions:\n    print(e.extraction_class, e.extraction_text)\n    print(f\"  char_interval: {e.char_interval}\")\n    print(f\"  attributes: {e.attributes}\")\n```\n\nSee `examples\u002Fbasic_extraction.py` for a runnable version and\n`examples\u002Frelationship_extraction.py` for using `extraction_class` +\n`attributes` to encode relationships between entities.\n\n## Writing good examples\n\nExamples drive model behavior. Follow these rules:\n\n1. `extraction_text` must be verbatim from the example text, not paraphrased\n2. List extractions in order of appearance in the text\n3. Each `extraction_class` should be consistent across examples\n4. Include attributes that match what you want extracted at runtime\n\nLangExtract can raise prompt-alignment warnings when an example's\n`extraction_text` values don't align cleanly to the example's `text`\n(failed alignment, or fuzzy\u002Flesser rather than exact). The validator does\nnot enforce rules 2–4 above — those are guidance to steer the model's\noutput, not checked invariants.\n\nTo fail fast on alignment issues during development, pass these kwargs\ndirectly to `lx.extract()` (both default to permissive):\n\n```python\nfrom langextract.prompt_validation import PromptValidationLevel\n\nresult = lx.extract(\n    ...,\n    prompt_validation_level=PromptValidationLevel.ERROR,  # default: WARNING\n    prompt_validation_strict=True,                          # default: False\n)\n```\n\nSee `references\u002Fprompt-validation.md` for level semantics and strict-mode\nbehavior.\n\n## Key parameters\n\n```python\nresult = lx.extract(\n    text_or_documents=text,          # str, URL, or list of Documents\n    fetch_urls=False,                 # True to fetch a URL input\n    prompt_description=prompt,        # what to extract (optional)\n    examples=examples,                # few-shot examples (required)\n    model_id=\"gemini-2.5-flash\",     # model to use\n    extraction_passes=1,              # >1 for higher recall (costs more)\n    max_char_buffer=1000,             # chunk size\n    batch_length=10,                  # chunks per batch\n    max_workers=10,                   # parallel workers (provider-dependent)\n    context_window_chars=None,        # cross-chunk context for coreference\n)\n```\n\n- `text_or_documents` accepts a URL string, which is fetched only when\n  `fetch_urls=True`; otherwise it is treated as text. Only enable fetching\n  for URLs from a trusted source, in a sandboxed process.\n- For full parallelism, keep `batch_length >= max_workers`. Parallel\n  processing via `max_workers` is provider-dependent; some providers\n  parallelize batched prompts, while others (such as the current Ollama\n  provider) process them sequentially.\n- `context_window_chars` includes characters from the previous chunk as\n  context for the current one, which helps with coreference and entity\n  continuity across chunk boundaries.\n- For multiple documents, pass a list of `lx.data.Document` — see\n  `examples\u002Fmultiple_documents.py`.\n\n## Working with results\n\n```python\n# Filter to grounded extractions only (have source positions)\ngrounded = [e for e in result.extractions if e.char_interval]\n\n# Access source position\nfor e in grounded:\n    start = e.char_interval.start_pos\n    end = e.char_interval.end_pos\n    matched_text = result.text[start:end]\n\n# Save to JSONL\nlx.io.save_annotated_documents(\n    [result], output_name=\"results.jsonl\", output_dir=\".\"\n)\n\n# Visualize from JSONL (shows first document)\nhtml = lx.visualize(\"results.jsonl\")\nwith open(\"visualization.html\", \"w\", encoding=\"utf-8\") as f:\n    if hasattr(html, \"data\"):\n        f.write(html.data)  # Jupyter\u002FColab\n    else:\n        f.write(html)\n\n# Or visualize an AnnotatedDocument directly\nhtml = lx.visualize(result)\n```\n\n## Provider selection\n\nThe default is Gemini. For other providers, see `references\u002Fproviders.md`,\nwhich covers:\n\n- OpenAI (JSON mode; fence behavior auto-configured)\n- Ollama (local models, `model_url`)\n- `ModelConfig` for advanced provider_kwargs (custom `base_url`, etc.)\n- Custom provider plugins via `router.register()`\n\n## Common issues\n\n**Extractions with `char_interval=None`**: the extraction could not be\nlocated in the source text. Common causes include paraphrased output,\nalignment misses, or hallucinated entities. Filter with\n`[e for e in result.extractions if e.char_interval]`. To tune alignment,\nsee `references\u002Fresolver-params.md`.\n\n**Prompt alignment warnings**: your examples have `extraction_text` that\ndoesn't match the example text verbatim. Fix the examples, or see\n`references\u002Fprompt-validation.md` to fail fast during development.\n\n**Slow on long documents**: `extraction_passes > 1` multiplies processing\ntime. Start with 1 and increase only if recall is insufficient.\n\n**Model selection**: `gemini-2.5-flash` is recommended for most tasks;\n`gemini-2.5-pro` for complex reasoning.\n\n## Further reading\n\n- `references\u002Fproviders.md` — OpenAI, Ollama, ModelConfig, custom plugins\n- `references\u002Fresolver-params.md` — fuzzy alignment tuning\n- `references\u002Fprompt-validation.md` — catching example issues early\n- `examples\u002F` — runnable scripts for each scenario above\n","# LangExtract Usage\n\nLangExtract extracts structured information from unstructured text using LLMs.\nThe main entry point is `lx.extract()`. Every extraction needs at least one\nexample and input text. `prompt_description` is optional but recommended.\n\n## Install\n\n```bash\npip install langextract\n\n# For OpenAI model support:\npip install langextract[openai]\n```\n\n## API keys\n\n```bash\n# Gemini (checks GEMINI_API_KEY then LANGEXTRACT_API_KEY)\nexport GEMINI_API_KEY=\"your_key\"\n\n# OpenAI (checks OPENAI_API_KEY then LANGEXTRACT_API_KEY)\nexport OPENAI_API_KEY=\"your_key\"\n\n# Ollama: no API key needed, just a running Ollama server\n```\n\nAuto-routing + env-default resolution is tuned for GPT-style model IDs\n(`gpt-4*`, `gpt-5*`, `gpt-6*`). For OpenAI-compatible endpoints or\nnon-GPT IDs, pass an explicit `ModelConfig` — see `references\u002Fproviders.md`.\n\n## Basic extraction\n\n```python\nimport langextract as lx\n\nexamples = [\n    lx.data.ExampleData(\n        text=\"Patient takes lisinopril 10mg daily for hypertension.\",\n        extractions=[\n            lx.data.Extraction(\n                extraction_class=\"medication\",\n                extraction_text=\"lisinopril\",\n                attributes={\"dose\": \"10mg\", \"frequency\": \"daily\"},\n            ),\n            lx.data.Extraction(\n                extraction_class=\"condition\",\n                extraction_text=\"hypertension\",\n                attributes={\"status\": \"active\"},\n            ),\n        ],\n    )\n]\n\nresult = lx.extract(\n    text_or_documents=\"Patient is prescribed metformin 500mg twice daily.\",\n    prompt_description=\"Extract medications and conditions with attributes.\",\n    examples=examples,\n    model_id=\"gemini-2.5-flash\",\n)\n\nfor e in result.extractions:\n    print(e.extraction_class, e.extraction_text)\n    print(f\"  char_interval: {e.char_interval}\")\n    print(f\"  attributes: {e.attributes}\")\n```\n\nSee `examples\u002Fbasic_extraction.py` for a runnable version and\n`examples\u002Frelationship_extraction.py` for using `extraction_class` +\n`attributes` to encode relationships between entities.\n\n## Writing good examples\n\nExamples drive model behavior. Follow these rules:\n\n1. `extraction_text` must be verbatim from the example text, not paraphrased\n2. List extractions in order of appearance in the text\n3. Each `extraction_class` should be consistent across examples\n4. Include attributes that match what you want extracted at runtime\n\nLangExtract can raise prompt-alignment warnings when an example's\n`extraction_text` values don't align cleanly to the example's `text`\n(failed alignment, or fuzzy\u002Flesser rather than exact). The validator does\nnot enforce rules 2–4 above — those are guidance to steer the model's\noutput, not checked invariants.\n\nTo fail fast on alignment issues during development, pass these kwargs\ndirectly to `lx.extract()` (both default to permissive):\n\n```python\nfrom langextract.prompt_validation import PromptValidationLevel\n\nresult = lx.extract(\n    ...,\n    prompt_validation_level=PromptValidationLevel.ERROR,  # default: WARNING\n    prompt_validation_strict=True,                          # default: False\n)\n```\n\nSee `references\u002Fprompt-validation.md` for level semantics and strict-mode\nbehavior.\n\n## Key parameters\n\n```python\nresult = lx.extract(\n    text_or_documents=text,          # str, URL, or list of Documents\n    fetch_urls=False,                 # True to fetch a URL input\n    prompt_description=prompt,        # what to extract (optional)\n    examples=examples,                # few-shot examples (required)\n    model_id=\"gemini-2.5-flash\",     # model to use\n    extraction_passes=1,              # >1 for higher recall (costs more)\n    max_char_buffer=1000,             # chunk size\n    batch_length=10,                  # chunks per batch\n    max_workers=10,                   # parallel workers (provider-dependent)\n    context_window_chars=None,        # cross-chunk context for coreference\n)\n```\n\n- `text_or_documents` accepts a URL string, which is fetched only when\n  `fetch_urls=True`; otherwise it is treated as text. Only enable fetching\n  for URLs from a trusted source, in a sandboxed process.\n- For full parallelism, keep `batch_length >= max_workers`. Parallel\n  processing via `max_workers` is provider-dependent; some providers\n  parallelize batched prompts, while others (such as the current Ollama\n  provider) process them sequentially.\n- `context_window_chars` includes characters from the previous chunk as\n  context for the current one, which helps with coreference and entity\n  continuity across chunk boundaries.\n- For multiple documents, pass a list of `lx.data.Document` — see\n  `examples\u002Fmultiple_documents.py`.\n\n## Working with results\n\n```python\n# Filter to grounded extractions only (have source positions)\ngrounded = [e for e in result.extractions if e.char_interval]\n\n# Access source position\nfor e in grounded:\n    start = e.char_interval.start_pos\n    end = e.char_interval.end_pos\n    matched_text = result.text[start:end]\n\n# Save to JSONL\nlx.io.save_annotated_documents(\n    [result], output_name=\"results.jsonl\", output_dir=\".\"\n)\n\n# Visualize from JSONL (shows first document)\nhtml = lx.visualize(\"results.jsonl\")\nwith open(\"visualization.html\", \"w\", encoding=\"utf-8\") as f:\n    if hasattr(html, \"data\"):\n        f.write(html.data)  # Jupyter\u002FColab\n    else:\n        f.write(html)\n\n# Or visualize an AnnotatedDocument directly\nhtml = lx.visualize(result)\n```\n\n## Provider selection\n\nThe default is Gemini. For other providers, see `references\u002Fproviders.md`,\nwhich covers:\n\n- OpenAI (JSON mode; fence behavior auto-configured)\n- Ollama (local models, `model_url`)\n- `ModelConfig` for advanced provider_kwargs (custom `base_url`, etc.)\n- Custom provider plugins via `router.register()`\n\n## Common issues\n\n**Extractions with `char_interval=None`**: the extraction could not be\nlocated in the source text. Common causes include paraphrased output,\nalignment misses, or hallucinated entities. Filter with\n`[e for e in result.extractions if e.char_interval]`. To tune alignment,\nsee `references\u002Fresolver-params.md`.\n\n**Prompt alignment warnings**: your examples have `extraction_text` that\ndoesn't match the example text verbatim. Fix the examples, or see\n`references\u002Fprompt-validation.md` to fail fast during development.\n\n**Slow on long documents**: `extraction_passes > 1` multiplies processing\ntime. Start with 1 and increase only if recall is insufficient.\n\n**Model selection**: `gemini-2.5-flash` is recommended for most tasks;\n`gemini-2.5-pro` for complex reasoning.\n\n## Further reading\n\n- `references\u002Fproviders.md` — OpenAI, Ollama, ModelConfig, custom plugins\n- `references\u002Fresolver-params.md` — fuzzy alignment tuning\n- `references\u002Fprompt-validation.md` — catching example issues early\n- `examples\u002F` — runnable scripts for each scenario above\n",{"name":5,"description":7},"main","7548803224677c8e810f76876ae9519b5708a18f","skills\u002Flangextract-usage",2751,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract","https:\u002F\u002Fpypi.org\u002Fproject\u002Flangextract\u002F","https:\u002F\u002Fgithub.com\u002Fgoogle","https:\u002F\u002Fopensource.google\u002F","Google ❤️ Open Source","2026-11-10 09:39:37",{"source":8,"skillName":5,"commands":61,"prompt":71,"zipAvailable":72},[62,65,68],{"tool":63,"command":64},"npx","npx skills add google\u002Flangextract --skill langextract-usage",{"tool":66,"command":67},"bunx","bunx skills add google\u002Flangextract --skill langextract-usage",{"tool":69,"command":70},"pnpm","pnpm dlx skills add google\u002Flangextract --skill langextract-usage","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002FSKILL.md",true,[74,80,84,88,94,98,102],{"path":75,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":79},"examples\u002Fbasic_extraction.py","SCRIPT","脚本",1664,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002Fexamples\u002Fbasic_extraction.py",{"path":81,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":82,"sourceHtmlUrl":83},"examples\u002Fmultiple_documents.py",1769,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002Fexamples\u002Fmultiple_documents.py",{"path":85,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":86,"sourceHtmlUrl":87},"examples\u002Frelationship_extraction.py",2215,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002Fexamples\u002Frelationship_extraction.py",{"path":89,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":92,"sourceHtmlUrl":93},"README.md","REFERENCE","参考文档",3633,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002FREADME.md",{"path":95,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fprompt-validation.md",1847,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002Freferences\u002Fprompt-validation.md",{"path":99,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":100,"sourceHtmlUrl":101},"references\u002Fproviders.md",4606,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002Freferences\u002Fproviders.md",{"path":103,"resourceType":90,"resourceTypeDesc":91,"sizeBytes":104,"sourceHtmlUrl":105},"references\u002Fresolver-params.md",2866,"https:\u002F\u002Fgithub.com\u002Fgoogle\u002Flangextract\u002Fblob\u002Fmain\u002Fskills\u002Flangextract-usage\u002Freferences\u002Fresolver-params.md",[]]