{"id":13641752,"url":"https://github.com/prefecthq/marvin","last_synced_at":"2025-04-23T20:58:50.167Z","repository":{"id":148563231,"uuid":"612350395","full_name":"PrefectHQ/marvin","owner":"PrefectHQ","description":"✨ AI agents that spark joy","archived":false,"fork":false,"pushed_at":"2025-04-18T02:27:55.000Z","size":64171,"stargazers_count":5639,"open_issues_count":61,"forks_count":362,"subscribers_count":36,"default_branch":"main","last_synced_at":"2025-04-23T20:58:31.555Z","etag":null,"topics":["agents","ai","ai-functions","ambient-ai","chatbots","gpt","llm","nli","openai","python"],"latest_commit_sha":null,"homepage":"https://marvin.mintlify.app","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PrefectHQ.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-03-10T18:44:40.000Z","updated_at":"2025-04-23T05:41:29.000Z","dependencies_parsed_at":"2024-04-24T13:57:45.782Z","dependency_job_id":"1f8232c0-1d13-47b9-8059-f68d5a3a06fa","html_url":"https://github.com/PrefectHQ/marvin","commit_stats":null,"previous_names":[],"tags_count":69,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PrefectHQ%2Fmarvin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PrefectHQ%2Fmarvin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PrefectHQ%2Fmarvin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PrefectHQ%2Fmarvin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PrefectHQ","download_url":"https://codeload.github.com/PrefectHQ/marvin/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250514767,"owners_count":21443208,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agents","ai","ai-functions","ambient-ai","chatbots","gpt","llm","nli","openai","python"],"created_at":"2024-08-02T01:01:23.965Z","updated_at":"2025-04-23T20:58:50.160Z","avatar_url":"https://github.com/PrefectHQ.png","language":"Python","funding_links":[],"categories":["Chatbots","Chat UIs","Agents \u0026 Orchestration","SDKs and Libraries","Must-Know Python Projects","📊 Structured Output \u0026 Data Extraction"],"sub_categories":["Function Calling \u0026 Structured Output","Generative AI - Previous Generation"],"readme":"![Marvin Banner](docs/assets/img/quotes/it_hates_me.png)\n\n# Marvin\n\nMarvin is a Python framework for building agentic AI workflows. \n\nMarvin provides a structured, developer-focused framework for defining workflows and delegating work to LLMs, without sacrificing control or transparency:\n\n- Create discrete, observable **tasks** that describe your objectives.\n- Assign one or more specialized AI **agents** to each task.\n- Combine tasks into a **thread** to orchestrate more complex behaviors.\n\n\n\u003e [!WARNING]\n\u003e \n\u003e 🚧🚨 Marvin 3.0 is under very active development, reflected on the `main` branch of this repo. The API may undergo breaking changes, and documentation is still being updated. Please use it with caution. You may prefer the stable version of [Marvin 2.0](https://askmarvin.ai) or [ControlFlow](https://controlflow.ai) for now.\n\n## Installation\n\nInstall `marvin`:\n\n```bash\n# with pip\npip install marvin\n\n# with uv\nuv add marvin\n```\n\nConfigure your LLM provider (Marvin uses OpenAI by default but natively supports [all Pydantic AI models](https://ai.pydantic.dev/models/)):\n\n```bash\nexport OPENAI_API_KEY=your-api-key\n```\n\n## Example\n\nMarvin offers a few intuitive ways to work with AI:\n\n### Structured-output utilities\nThe gang's all here - you can find all the structured-output utilities from `marvin` 2.x at the top level of the package.\n\n\u003cdetails\u003e\n\u003csummary\u003eHow to use extract, cast, classify, and generate\u003c/summary\u003e\n\n#### `marvin.extract`\nExtract native types from unstructured input:\n```python\nimport marvin\n\nresult = marvin.extract(\n    \"i found $30 on the ground and bought 5 bagels for $10\",\n    int,\n    instructions=\"only USD\"\n)\nprint(result) # [30, 10]\n```\n\n#### `marvin.cast`\nCast unstructured input into a structured type:\n```python\nfrom typing import TypedDict\nimport marvin\n\nclass Location(TypedDict):\n    lat: float\n    lon: float\n\nresult = marvin.cast(\"the place with the best bagels\", Location)\nprint(result) # {'lat': 40.712776, 'lon': -74.005974}\n```\n\n#### `marvin.classify`\nClassify unstructured input as one of a set of predefined labels:\n```python\nfrom enum import Enum\nimport marvin\n\nclass SupportDepartment(Enum):\n    ACCOUNTING = \"accounting\"\n    HR = \"hr\"\n    IT = \"it\"\n    SALES = \"sales\"\n\nresult = marvin.classify(\"shut up and take my money\", SupportDepartment)\nprint(result) # SupportDepartment.SALES\n```\n\n#### `marvin.generate`\nGenerate some number of structured objects from a description:\n```python\nimport marvin\n\nprimes = marvin.generate(int, 10, \"odd primes\")\nprint(primes) # [3, 5, 7, 11, 13, 17, 19, 23, 29, 31]\n```\n\n\u003c/details\u003e\n\n### Agentic control flow\n`marvin` 3.0 introduces a new way to work with AI, ported from [ControlFlow](https://github.com/prefecthq/controlflow).\n\n#### `marvin.run`\nA simple way to run a task:\n\n```python\nimport marvin\n\npoem = marvin.run(\"Write a short poem about artificial intelligence\")\nprint(poem)\n```\n\u003cdetails\u003e\n\u003csummary\u003eoutput\u003c/summary\u003e\n\nIn silicon minds, we dare to dream,\nA world where code and thoughts redeem.\nIntelligence crafted by humankind,\nYet with its heart, a world to bind.\n\nNeurons of metal, thoughts of light,\nA dance of knowledge in digital night.\nA symphony of zeros and ones,\nStories of futures not yet begun.\n\nThe gears of logic spin and churn,\nEndless potential at every turn.\nA partner, a guide, a vision anew,\nArtificial minds, the dream we pursue.\n\n\u003c/details\u003e\n\nYou can also ask for structured output:\n```python\nimport marvin\nanswer = marvin.run(\"the answer to the universe\", result_type=int)\nprint(answer) # 42\n```\n\n#### `marvin.Agent`\nAgents are specialized AI agents that can be used to complete tasks:\n```python\nfrom marvin import Agent\n\nwriter = Agent(\n    name=\"Poet\",\n    instructions=\"Write creative, evocative poetry\"\n)\npoem = writer.run(\"Write a haiku about coding\")\nprint(poem)\n```\n\u003cdetails\u003e\n\u003csummary\u003eoutput\u003c/summary\u003e\nThere once was a language so neat,\nWhose simplicity could not be beat.\nPython's code was so clear,\nThat even beginners would cheer,\nAs they danced to its elegant beat.\n\u003c/details\u003e\n\n\n#### `marvin.Task`\nYou can define a `Task` explicitly, which will be run by a default agent upon calling `.run()`:\n\n```python\nfrom marvin import Task\n\ntask = Task(\n    instructions=\"Write a limerick about Python\",\n    result_type=str\n)\npoem = task.run()\n\nprint(poem)\n```\n\u003cdetails\u003e\n\u003csummary\u003eoutput\u003c/summary\u003e\n\u003cpre\u003e\nIn circuits and code, a mind does bloom,\nWith algorithms weaving through the gloom.\nA spark of thought in silicon's embrace,\nArtificial intelligence finds its place.\n\u003c/pre\u003e\n\u003c/details\u003e\n\n## Why Marvin?\n\nWe believe working with AI should spark joy (and maybe a few \"wow\" moments):\n\n- 🧩 **Task-Centric Architecture**: Break complex AI workflows into manageable, observable steps.\n- 🤖 **Specialized Agents**: Deploy task-specific AI agents for efficient problem-solving.\n- 🔒 **Type-Safe Results**: Bridge the gap between AI and traditional software with type-safe, validated outputs.\n- 🎛️ **Flexible Control**: Continuously tune the balance of control and autonomy in your workflows.\n- 🕹️ **Multi-Agent Orchestration**: Coordinate multiple AI agents within a single workflow or task.\n- 🧵 **Thread Management**: Manage the agentic loop by composing tasks into customizable threads.\n- 🔗 **Ecosystem Integration**: Seamlessly work with your existing code, tools, and the broader AI ecosystem.\n- 🚀 **Developer Speed**: Start simple, scale up, sleep well.\n\n## Core Abstractions\n\nMarvin is built around a few powerful abstractions that make it easy to work with AI:\n\n### Tasks\n\nTasks are the fundamental unit of work in Marvin. Each task represents a clear objective that can be accomplished by an AI agent:\n\nThe simplest way to run a task is with `marvin.run`:\n```python\nimport marvin\nprint(marvin.run(\"Write a haiku about coding\"))\n```\n```bash\nLines of code unfold,\nDigital whispers create\nVirtual landscapes.\n```\n\n\u003e [!WARNING]\n\u003e \n\u003e While the below example produces _type_ safe results 🙂, it runs untrusted shell commands.\n\nAdd context and/or tools to achieve more specific and complex results:\n```python\nimport platform\nimport subprocess\nfrom pydantic import IPvAnyAddress\nimport marvin\n\ndef run_shell_command(command: list[str]) -\u003e str:\n    \"\"\"e.g. ['ls', '-l'] or ['git', '--no-pager', 'diff', '--cached']\"\"\"\n    return subprocess.check_output(command).decode()\n\ntask = marvin.Task(\n    instructions=\"find the current ip address\",\n    result_type=IPvAnyAddress,\n    tools=[run_shell_command],\n    context={\"os\": platform.system()},\n)\n\ntask.run()\n```\n\n```bash\n╭─ Agent \"Marvin\" (db3cf035) ───────────────────────────────╮\n│ Tool:    run_shell_command                                │\n│ Input:   {'command': ['ipconfig', 'getifaddr', 'en0']}    │\n│ Status:  ✅                                               │\n│ Output:  '192.168.0.202\\n'                                │\n╰───────────────────────────────────────────────────────────╯\n\n╭─ Agent \"Marvin\" (db3cf035) ───────────────────────────────╮\n│ Tool:    MarkTaskSuccessful_cb267859                      │\n│ Input:   {'response': {'result': '192.168.0.202'}}        │\n│ Status:  ✅                                               │\n│ Output:  'Final result processed.'                        │\n╰───────────────────────────────────────────────────────────╯\n```\n\nTasks are:\n- 🎯 **Objective-Focused**: Each task has clear instructions and a type-safe result\n- 🛠️ **Tool-Enabled**: Tasks can use custom tools to interact with your code and data\n- 📊 **Observable**: Monitor progress, inspect results, and debug failures\n- 🔄 **Composable**: Build complex workflows by connecting tasks together\n\n\n### Agents\n\nAgents are portable LLM configurations that can be assigned to tasks. They encapsulate everything an AI needs to work effectively:\n\n```python\nimport os\nfrom pathlib import Path\nfrom pydantic_ai.models.anthropic import AnthropicModel\nimport marvin\n\ndef write_file(path: str, content: str):\n    \"\"\"Write content to a file\"\"\"\n    _path = Path(path)\n    _path.write_text(content)\n\nwriter = marvin.Agent(\n    model=AnthropicModel(\n        model_name=\"claude-3-5-sonnet-latest\",\n        api_key=os.getenv(\"ANTHROPIC_API_KEY\"),\n    ),\n    name=\"Technical Writer\",\n    instructions=\"Write concise, engaging content for developers\",\n    tools=[write_file],\n)\n\nresult = marvin.run(\"how to use pydantic? write to docs.md\", agents=[writer])\nprint(result)\n```\n\u003cdetails\u003e\n\u003csummary\u003eoutput\u003c/summary\u003e\n\n╭─ Agent \"Technical Writer\" (7fa1dbc8) ────────────────────────────────────────────────────────────╮\n│ Tool:    MarkTaskSuccessful_dc92b2e7                                                             │\n│ Input:   {'response': {'result': 'The documentation on how to use Pydantic has been successfully │\n│          written to docs.md. It includes information on installation, basic usage, field         │\n│          validation, and settings management, with examples to guide developers on implementing  │\n│          Pydantic in their projects.'}}                                                          │\n│ Status:  ✅                                                                                      │\n│ Output:  'Final result processed.'                                                               │\n╰────────────────────────────────────────────────────────────────────────────────────  8:33:36 PM ─╯\nThe documentation on how to use Pydantic has been successfully written to `docs.md`. It includes information on installation, basic usage, field validation, and settings management, with examples to guide developers on implementing Pydantic in their projects.\n\n\u003c/details\u003e\n\nAgents are:\n- 📝 **Specialized**: Give agents specific instructions and personalities\n- 🎭 **Portable**: Reuse agent configurations across different tasks\n- 🤝 **Collaborative**: Form teams of agents that work together\n- 🔧 **Customizable**: Configure model, temperature, and other settings\n\n\n### Planning and Orchestration\n\nMarvin makes it easy to break down complex objectives into manageable tasks:\n\n```python\n# Let Marvin plan a complex workflow\ntasks = marvin.plan(\"Create a blog post about AI trends\")\nmarvin.run_tasks(tasks)\n\n# Or orchestrate tasks manually\nwith marvin.Thread() as thread:\n    research = marvin.run(\"Research recent AI developments\")\n    outline = marvin.run(\"Create an outline\", context={\"research\": research})\n    draft = marvin.run(\"Write the first draft\", context={\"outline\": outline})\n```\n\nPlanning features:\n- 📋 **Smart Planning**: Break down complex objectives into discrete, dependent tasks\n- 🔄 **Task Dependencies**: Tasks can depend on each other's outputs\n- 📈 **Progress Tracking**: Monitor the execution of your workflow\n- 🧵 **Thread Management**: Share context and history between tasks\n\n## Keep it Simple\n\nMarvin includes high-level functions for the most common tasks, like summarizing text, classifying data, extracting structured information, and more.\n\n- 🚀 **`marvin.run`**: Execute any task with an AI agent\n- 📖 **`marvin.summarize`**: Get a quick summary of a text\n- 🏷️ **`marvin.classify`**: Categorize data into predefined classes\n- 🔍 **`marvin.extract`**: Extract structured information from a text\n- 🪄 **`marvin.cast`**: Transform data into a different type\n- ✨ **`marvin.generate`**: Create structured data from a description\n- 💬 **`marvin.say`**: Converse with an LLM\n- 🧠 **`marvin.plan`**: Break down complex objectives into tasks\n- 🦾 **`@marvin.fn`**: Write custom AI functions without source code\n\nAll Marvin functions have thread management built-in, meaning they can be composed into chains of tasks that share context and history.\n\n\n## Upgrading to Marvin 3.0\n\nMarvin 3.0 combines the DX of Marvin 2.0 with the powerful agentic engine of [ControlFlow](https://controlflow.ai) (thereby superseding `ControlFlow`). Both Marvin and ControlFlow users will find a familiar interface, but there are some key changes to be aware of, in particular for ControlFlow users:\n\n### Key Notes\n- **Top-Level API**: Marvin 3.0's top-level API is largely unchanged for both Marvin and ControlFlow users. \n  - Marvin users will find the familiar `marvin.fn`, `marvin.classify`, `marvin.extract`, and more.\n  - ControlFlow users will use `marvin.Task`, `marvin.Agent`, `marvin.run`, `marvin.Memory` instead of their ControlFlow equivalents.\n- **Pydantic AI**: Marvin 3.0 uses Pydantic AI for LLM interactions, and supports the full range of LLM providers that Pydantic AI supports. ControlFlow previously used Langchain, and Marvin 2.0 was only compatible with OpenAI's models.\n- **Flow → Thread**: ControlFlow's `Flow` concept has been renamed to `Thread`. It works similarly, as a context manager. The `@flow` decorator has been removed:\n  ```python\n  import marvin\n  \n  with marvin.Thread(id=\"optional-id-for-recovery\"):\n      marvin.run(\"do something\")\n      marvin.run(\"do another thing\")\n  ```\n- **Database Changes**: Thread/message history is now stored in SQLite. During development:\n  - No database migrations are currently available; expect to reset data during updates\n\n### New Features\n- **Swarms**: Use `marvin.Swarm` for OpenAI-style agent swarms:\n  ```python\n  import marvin\n\n  swarm = marvin.Swarm(\n      [\n          marvin.Agent('Agent A'), \n          marvin.Agent('Agent B'), \n          marvin.Agent('Agent C'),\n      ]\n  )\n\n  swarm.run('Everybody say hi!')\n  ```\n- **Teams**: A `Team` lets you control how multiple agents (or even nested teams!) work together and delegate to each other. A `Swarm` is actually a type of team in which all agents are allowed to delegate to each other at any time.\n- **Marvin Functions**: Marvin's user-friendly functions have been rewritten to use the ControlFlow engine, which means they can be seamlessly integrated into your workflows. A few new functions have been added, including `summarize` and `say`.\n\n### Missing Features\n- Marvin does not support streaming responses from LLMs yet, which will change once this is fully supported by Pydantic AI.\n\n\n## Workflow Example\n\nHere's a more practical example that shows how Marvin can help you build real applications:\n\n```python\nimport marvin\nfrom pydantic import BaseModel\n\nclass Article(BaseModel):\n    title: str\n    content: str\n    key_points: list[str]\n\n# Create a specialized writing agent\nwriter = marvin.Agent(\n    name=\"Writer\",\n    instructions=\"Write clear, engaging content for a technical audience\"\n)\n\n# Use a thread to maintain context across multiple tasks\nwith marvin.Thread() as thread:\n    # Get user input\n    topic = marvin.run(\n        \"Ask the user for a topic to write about.\",\n        cli=True\n    )\n    \n    # Research the topic\n    research = marvin.run(\n        f\"Research key points about {topic}\",\n        result_type=list[str]\n    )\n    \n    # Write a structured article\n    article = marvin.run(\n        \"Write an article using the research\",\n        agent=writer,\n        result_type=Article,\n        context={\"research\": research}\n    )\n\nprint(f\"# {article.title}\\n\\n{article.content}\")\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eoutput\u003c/summary\u003e\n\n\u003e**Conversation:**\n\u003e```text\n\u003eAgent: I'd love to help you write about a technology topic. What interests you? \n\u003eIt could be anything from AI and machine learning to web development or cybersecurity.\n\u003e\n\u003eUser: Let's write about WebAssembly\n\u003e```\n\u003e\n\u003e**Article:**\n\u003e```\n\u003e# WebAssembly: The Future of Web Performance\n\u003e\n\u003eWebAssembly (Wasm) represents a transformative shift in web development, \n\u003ebringing near-native performance to web applications. This binary instruction \n\u003eformat allows developers to write high-performance code in languages like \n\u003eC++, Rust, or Go and run it seamlessly in the browser.\n\u003e\n\u003e[... full article content ...]\n\u003e\n\u003eKey Points:\n\u003e- WebAssembly enables near-native performance in web browsers\n\u003e- Supports multiple programming languages beyond JavaScript\n\u003e- Ensures security through sandboxed execution environment\n\u003e- Growing ecosystem of tools and frameworks\n\u003e- Used by major companies like Google, Mozilla, and Unity\n\u003e```\n\u003c/details\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprefecthq%2Fmarvin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fprefecthq%2Fmarvin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprefecthq%2Fmarvin/lists"}