pydantic_ai.agent
Agent
dataclass
Bases: AbstractAgent[AgentDepsT, OutputDataT]
Class for defining "agents" - a way to have a specific type of "conversation" with an LLM.
Agents are generic in the dependency type they take AgentDepsT
and the output type they return, OutputDataT.
By default, if neither generic parameter is customised, agents have type Agent[None, str].
Minimal usage example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> The capital of France is Paris.
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 | |
__init__
__init__(
model: Model | KnownModelName | str | None = None,
*,
output_type: OutputSpec[OutputDataT] = str,
instructions: AgentInstructions[AgentDepsT] = None,
system_prompt: str | Sequence[str] = (),
deps_type: type[AgentDepsT] = NoneType,
name: str | None = None,
description: (
TemplateStr[AgentDepsT] | str | None
) = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
retries: int = 1,
validation_context: (
Any | Callable[[RunContext[AgentDepsT]], Any]
) = None,
output_retries: int | None = None,
tools: Sequence[
Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]
] = (),
prepare_tools: (
ToolsPrepareFunc[AgentDepsT] | None
) = None,
prepare_output_tools: (
ToolsPrepareFunc[AgentDepsT] | None
) = None,
toolsets: (
Sequence[AgentToolset[AgentDepsT]] | None
) = None,
defer_model_check: bool = False,
end_strategy: EndStrategy = "early",
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
history_processors: (
Sequence[HistoryProcessor[AgentDepsT]] | None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[AgentDepsT]] | None
) = None
) -> None
__init__(
model: Model | KnownModelName | str | None = None,
*,
output_type: OutputSpec[OutputDataT] = str,
instructions: AgentInstructions[AgentDepsT] = None,
system_prompt: str | Sequence[str] = (),
deps_type: type[AgentDepsT] = NoneType,
name: str | None = None,
description: (
TemplateStr[AgentDepsT] | str | None
) = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
retries: int = 1,
validation_context: (
Any | Callable[[RunContext[AgentDepsT]], Any]
) = None,
output_retries: int | None = None,
tools: Sequence[
Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]
] = (),
prepare_tools: (
ToolsPrepareFunc[AgentDepsT] | None
) = None,
prepare_output_tools: (
ToolsPrepareFunc[AgentDepsT] | None
) = None,
mcp_servers: Sequence[MCPServer] = (),
defer_model_check: bool = False,
end_strategy: EndStrategy = "early",
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
history_processors: (
Sequence[HistoryProcessor[AgentDepsT]] | None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[AgentDepsT]] | None
) = None
) -> None
__init__(
model: Model | KnownModelName | str | None = None,
*,
output_type: OutputSpec[OutputDataT] = str,
instructions: AgentInstructions[AgentDepsT] = None,
system_prompt: str | Sequence[str] = (),
deps_type: type[AgentDepsT] = NoneType,
name: str | None = None,
description: (
TemplateStr[AgentDepsT] | str | None
) = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
retries: int = 1,
validation_context: (
Any | Callable[[RunContext[AgentDepsT]], Any]
) = None,
output_retries: int | None = None,
tools: Sequence[
Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]
] = (),
prepare_tools: (
ToolsPrepareFunc[AgentDepsT] | None
) = None,
prepare_output_tools: (
ToolsPrepareFunc[AgentDepsT] | None
) = None,
toolsets: (
Sequence[AgentToolset[AgentDepsT]] | None
) = None,
defer_model_check: bool = False,
end_strategy: EndStrategy = "early",
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
history_processors: (
Sequence[HistoryProcessor[AgentDepsT]] | None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[AgentDepsT]] | None
) = None,
**_deprecated_kwargs: Any
)
Create an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model | KnownModelName | str | None
|
The default model to use for this agent, if not provided,
you must provide the model when calling it. We allow |
None
|
output_type
|
OutputSpec[OutputDataT]
|
The type of the output data, used to validate the data returned by the model,
defaults to |
str
|
instructions
|
AgentInstructions[AgentDepsT]
|
Instructions to use for this agent, you can also register instructions via a function with
|
None
|
system_prompt
|
str | Sequence[str]
|
Static system prompts to use for this agent, you can also register system
prompts via a function with |
()
|
deps_type
|
type[AgentDepsT]
|
The type used for dependency injection, this parameter exists solely to allow you to fully
parameterize the agent, and therefore get the best out of static type checking.
If you're not using deps, but want type checking to pass, you can set |
NoneType
|
name
|
str | None
|
The name of the agent, used for logging. If |
None
|
description
|
TemplateStr[AgentDepsT] | str | None
|
A human-readable description of the agent, attached to the agent run span as
|
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional model request settings to use for this agent's runs, by default.
Can be a static |
None
|
retries
|
int
|
The default number of retries to allow for tool calls and output validation, before raising an error. For model request retries, see the HTTP Request Retries documentation. |
1
|
validation_context
|
Any | Callable[[RunContext[AgentDepsT]], Any]
|
Pydantic validation context used to validate tool arguments and outputs. |
None
|
output_retries
|
int | None
|
The maximum number of retries to allow for output validation, defaults to |
None
|
tools
|
Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]]
|
Tools to register with the agent, you can also register tools via the decorators
|
()
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]]
|
The builtin tools that the agent will use. This depends on the model, as some models may not support certain tools. If the model doesn't support the builtin tools, an error will be raised. |
()
|
prepare_tools
|
ToolsPrepareFunc[AgentDepsT] | None
|
Custom function to prepare the tool definition of all tools for each step, except output tools.
This is useful if you want to customize the definition of multiple tools or you want to register
a subset of tools for a given step. See |
None
|
prepare_output_tools
|
ToolsPrepareFunc[AgentDepsT] | None
|
Custom function to prepare the tool definition of all output tools for each step.
This is useful if you want to customize the definition of multiple output tools or you want to register
a subset of output tools for a given step. See |
None
|
toolsets
|
Sequence[AgentToolset[AgentDepsT]] | None
|
Toolsets to register with the agent, including MCP servers and functions which take a run context
and return a toolset. See |
None
|
defer_model_check
|
bool
|
by default, if you provide a named model,
it's evaluated to create a |
False
|
end_strategy
|
EndStrategy
|
Strategy for handling tool calls that are requested alongside a final result.
See |
'early'
|
instrument
|
InstrumentationSettings | bool | None
|
Set to True to automatically instrument with OpenTelemetry,
which will use Logfire if it's configured.
Set to an instance of |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to store with each run.
Provide a dictionary of primitives, or a callable returning one
computed from the |
None
|
history_processors
|
Sequence[HistoryProcessor[AgentDepsT]] | None
|
Optional list of callables to process the message history before sending it to the model. Each processor takes a list of messages and returns a modified list of messages. Processors can be sync or async and are applied in sequence. |
None
|
event_stream_handler
|
EventStreamHandler[AgentDepsT] | None
|
Optional handler for events from the model's streaming response and the agent's execution of tools. |
None
|
tool_timeout
|
float | None
|
Default timeout in seconds for tool execution. If a tool takes longer than this, the tool is considered to have failed and a retry prompt is returned to the model (counting towards the retry limit). Individual tools can override this with their own timeout. Defaults to None (no timeout). |
None
|
max_concurrency
|
AnyConcurrencyLimit
|
Optional limit on concurrent agent runs. Can be an integer for simple limiting,
a |
None
|
capabilities
|
Sequence[AbstractCapability[AgentDepsT]] | None
|
Optional list of capabilities to configure the agent with.
Built-in capabilities include [ |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
end_strategy
instance-attribute
end_strategy: EndStrategy = end_strategy
The strategy for handling multiple tool calls when a final result is found.
'early'(default): Output tools are executed first. Once a valid final result is found, remaining function and output tool calls are skipped'exhaustive': Output tools are executed first, then all function tools are executed. The first valid output tool result becomes the final output
model_settings
instance-attribute
model_settings: AgentModelSettings[AgentDepsT] | None = (
model_settings
)
Optional model request settings to use for this agent's runs, by default.
Can be a static ModelSettings dict or a callable that takes a
RunContext and returns ModelSettings.
Callables are called before each model request, allowing dynamic per-step settings.
Note, if model_settings is also provided at run time, those settings will be merged
on top of the agent-level settings, with the run-level argument taking priority.
instrument
instance-attribute
instrument: InstrumentationSettings | bool | None = (
instrument
)
Options to automatically instrument with OpenTelemetry.
from_spec
classmethod
from_spec(
spec: dict[str, Any] | AgentSpec,
*,
custom_capability_types: Sequence[
type[AbstractCapability[Any]]
] = (),
model: Model | KnownModelName | str | None = None,
output_type: OutputSpec[Any] = str,
instructions: AgentInstructions[Any] = None,
system_prompt: str | Sequence[str] = (),
name: str | None = None,
description: str | None = None,
model_settings: ModelSettings | None = None,
retries: int | None = None,
validation_context: Any = None,
output_retries: int | None = None,
tools: Sequence[
Tool[Any] | ToolFuncEither[Any, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[Any]
] = (),
prepare_tools: ToolsPrepareFunc[Any] | None = None,
prepare_output_tools: (
ToolsPrepareFunc[Any] | None
) = None,
toolsets: Sequence[AgentToolset[Any]] | None = None,
defer_model_check: bool = False,
end_strategy: EndStrategy | None = None,
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[Any] | None = None,
history_processors: (
Sequence[HistoryProcessor[Any]] | None
) = None,
event_stream_handler: (
EventStreamHandler[Any] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[Any]] | None
) = None
) -> Agent[None, str]
from_spec(
spec: dict[str, Any] | AgentSpec,
*,
deps_type: type[T],
custom_capability_types: Sequence[
type[AbstractCapability[Any]]
] = (),
model: Model | KnownModelName | str | None = None,
output_type: OutputSpec[Any] = str,
instructions: AgentInstructions[Any] = None,
system_prompt: str | Sequence[str] = (),
name: str | None = None,
description: str | None = None,
model_settings: ModelSettings | None = None,
retries: int | None = None,
validation_context: Any = None,
output_retries: int | None = None,
tools: Sequence[
Tool[Any] | ToolFuncEither[Any, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[Any]
] = (),
prepare_tools: ToolsPrepareFunc[Any] | None = None,
prepare_output_tools: (
ToolsPrepareFunc[Any] | None
) = None,
toolsets: Sequence[AgentToolset[Any]] | None = None,
defer_model_check: bool = False,
end_strategy: EndStrategy | None = None,
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[Any] | None = None,
history_processors: (
Sequence[HistoryProcessor[Any]] | None
) = None,
event_stream_handler: (
EventStreamHandler[Any] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[Any]] | None
) = None
) -> Agent[T, str]
from_spec(
spec: dict[str, Any] | AgentSpec,
*,
deps_type: type[Any] = type(None),
custom_capability_types: Sequence[
type[AbstractCapability[Any]]
] = (),
model: Model | KnownModelName | str | None = None,
output_type: OutputSpec[Any] = str,
instructions: AgentInstructions[Any] = None,
system_prompt: str | Sequence[str] = (),
name: str | None = None,
description: str | None = None,
model_settings: ModelSettings | None = None,
retries: int | None = None,
validation_context: Any = None,
output_retries: int | None = None,
tools: Sequence[
Tool[Any] | ToolFuncEither[Any, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[Any]
] = (),
prepare_tools: ToolsPrepareFunc[Any] | None = None,
prepare_output_tools: (
ToolsPrepareFunc[Any] | None
) = None,
toolsets: Sequence[AgentToolset[Any]] | None = None,
defer_model_check: bool = False,
end_strategy: EndStrategy | None = None,
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[Any] | None = None,
history_processors: (
Sequence[HistoryProcessor[Any]] | None
) = None,
event_stream_handler: (
EventStreamHandler[Any] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[Any]] | None
) = None
) -> Agent[Any, Any]
Construct an Agent from a spec dict or AgentSpec.
This allows defining agents declaratively in YAML/JSON/dict form.
Keyword arguments supplement the spec: scalar spec fields (like name,
retries) are used as defaults that explicit arguments override, while
capabilities from both sources are merged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
dict[str, Any] | AgentSpec
|
The agent specification, either a dict or an |
required |
deps_type
|
type[Any]
|
The type of the dependencies for the agent. When provided,
template strings in capabilities (e.g. |
type(None)
|
custom_capability_types
|
Sequence[type[AbstractCapability[Any]]]
|
Additional capability classes to make available beyond the built-in defaults. |
()
|
model
|
Model | KnownModelName | str | None
|
Override the model from the spec. |
None
|
output_type
|
OutputSpec[Any]
|
The type of the output data, defaults to |
str
|
instructions
|
AgentInstructions[Any]
|
Instructions for the agent. |
None
|
system_prompt
|
str | Sequence[str]
|
Static system prompts. |
()
|
name
|
str | None
|
The agent name, overrides spec |
None
|
description
|
str | None
|
The agent description, overrides spec |
None
|
model_settings
|
ModelSettings | None
|
Model request settings. |
None
|
retries
|
int | None
|
Default retries for tool calls and output validation, overrides spec |
None
|
validation_context
|
Any
|
Pydantic validation context for tool arguments and outputs. |
None
|
output_retries
|
int | None
|
Max retries for output validation, overrides spec |
None
|
tools
|
Sequence[Tool[Any] | ToolFuncEither[Any, ...]]
|
Tools to register with the agent. |
()
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[Any]]
|
Builtin tools for the agent. |
()
|
prepare_tools
|
ToolsPrepareFunc[Any] | None
|
Custom function to prepare tool definitions. |
None
|
prepare_output_tools
|
ToolsPrepareFunc[Any] | None
|
Custom function to prepare output tool definitions. |
None
|
toolsets
|
Sequence[AgentToolset[Any]] | None
|
Toolsets to register with the agent. |
None
|
defer_model_check
|
bool
|
Defer model evaluation until first run. |
False
|
end_strategy
|
EndStrategy | None
|
Strategy for tool calls alongside a final result, overrides spec |
None
|
instrument
|
InstrumentationSettings | bool | None
|
Instrumentation settings, overrides spec |
None
|
metadata
|
AgentMetadata[Any] | None
|
Metadata to store with each run, overrides spec |
None
|
history_processors
|
Sequence[HistoryProcessor[Any]] | None
|
Processors for message history. |
None
|
event_stream_handler
|
EventStreamHandler[Any] | None
|
Handler for streaming events. |
None
|
tool_timeout
|
float | None
|
Default timeout for tool execution, overrides spec |
None
|
max_concurrency
|
AnyConcurrencyLimit
|
Limit on concurrent agent runs. |
None
|
capabilities
|
Sequence[AbstractCapability[Any]] | None
|
Additional capabilities merged with those from the spec. |
None
|
Returns:
| Type | Description |
|---|---|
Agent[Any, Any]
|
A new Agent instance. |
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | |
from_file
classmethod
from_file(
path: Path | str,
*,
custom_capability_types: Sequence[
type[AbstractCapability[Any]]
] = (),
model: Model | KnownModelName | str | None = None,
output_type: OutputSpec[Any] = str,
instructions: AgentInstructions[Any] = None,
system_prompt: str | Sequence[str] = (),
name: str | None = None,
description: str | None = None,
model_settings: ModelSettings | None = None,
retries: int | None = None,
validation_context: Any = None,
output_retries: int | None = None,
tools: Sequence[
Tool[Any] | ToolFuncEither[Any, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[Any]
] = (),
prepare_tools: ToolsPrepareFunc[Any] | None = None,
prepare_output_tools: (
ToolsPrepareFunc[Any] | None
) = None,
toolsets: Sequence[AgentToolset[Any]] | None = None,
defer_model_check: bool = False,
end_strategy: EndStrategy | None = None,
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[Any] | None = None,
history_processors: (
Sequence[HistoryProcessor[Any]] | None
) = None,
event_stream_handler: (
EventStreamHandler[Any] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[Any]] | None
) = None
) -> Agent[None, str]
from_file(
path: Path | str,
*,
deps_type: type[T],
custom_capability_types: Sequence[
type[AbstractCapability[Any]]
] = (),
model: Model | KnownModelName | str | None = None,
output_type: OutputSpec[Any] = str,
instructions: AgentInstructions[Any] = None,
system_prompt: str | Sequence[str] = (),
name: str | None = None,
description: str | None = None,
model_settings: ModelSettings | None = None,
retries: int | None = None,
validation_context: Any = None,
output_retries: int | None = None,
tools: Sequence[
Tool[Any] | ToolFuncEither[Any, ...]
] = (),
builtin_tools: Sequence[
AbstractBuiltinTool | BuiltinToolFunc[Any]
] = (),
prepare_tools: ToolsPrepareFunc[Any] | None = None,
prepare_output_tools: (
ToolsPrepareFunc[Any] | None
) = None,
toolsets: Sequence[AgentToolset[Any]] | None = None,
defer_model_check: bool = False,
end_strategy: EndStrategy | None = None,
instrument: (
InstrumentationSettings | bool | None
) = None,
metadata: AgentMetadata[Any] | None = None,
history_processors: (
Sequence[HistoryProcessor[Any]] | None
) = None,
event_stream_handler: (
EventStreamHandler[Any] | None
) = None,
tool_timeout: float | None = None,
max_concurrency: AnyConcurrencyLimit = None,
capabilities: (
Sequence[AbstractCapability[Any]] | None
) = None
) -> Agent[T, str]
Construct an Agent from a YAML or JSON spec file.
This is a convenience method equivalent to
Agent.from_spec(AgentSpec.from_file(path), ...).
The file format is inferred from the extension (.yaml/.yml or .json).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
Path to the spec file. |
required |
**kwargs
|
Any
|
All other arguments are forwarded to [ |
{}
|
Returns:
| Type | Description |
|---|---|
Agent[Any, Any]
|
A new Agent instance. |
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 | |
instrument_all
staticmethod
instrument_all(
instrument: InstrumentationSettings | bool = True,
) -> None
Set the instrumentation options for all agents where instrument is not set.
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
794 795 796 797 | |
model
property
writable
model: Model | KnownModelName | str | None
The default model configured for this agent.
name
property
writable
name: str | None
The name of the agent, used for logging.
If None, we try to infer the agent name from the call frame when the agent is first run.
description
property
writable
description: str | None
A human-readable description of the agent.
If the description is a TemplateStr, returns the raw template source. The rendered description is available at runtime via OTel span attributes.
output_type
property
output_type: OutputSpec[OutputDataT]
The type of data output by agent runs, used to validate the data returned by the model, defaults to str.
event_stream_handler
property
event_stream_handler: EventStreamHandler[AgentDepsT] | None
Optional handler for events from the model's streaming response and the agent's execution of tools.
iter
async
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
AgentRun[AgentDepsT, OutputDataT]
]
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
AgentRun[AgentDepsT, RunOutputDataT]
]
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[Any] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[AgentRun[AgentDepsT, Any]]
A contextmanager which can be used to iterate over the agent graph's nodes as they are executed.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
AgentRun object. The AgentRun can be used to async-iterate over the nodes of the graph as they are
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
stream of events coming from the execution of tools.
The AgentRun also provides methods to access the full message history, new messages, and usage statistics,
and the final result of the run once it has completed.
For more details, see the documentation of AgentRun.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print(agent_run.result.output)
#> The capital of France is Paris.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[Any] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[AgentRun[AgentDepsT, Any]]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 | |
override
override(
*,
name: str | Unset = UNSET,
deps: AgentDepsT | Unset = UNSET,
model: Model | KnownModelName | str | Unset = UNSET,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | Unset
) = UNSET,
tools: (
Sequence[
Tool[AgentDepsT]
| ToolFuncEither[AgentDepsT, ...]
]
| Unset
) = UNSET,
instructions: (
AgentInstructions[AgentDepsT] | Unset
) = UNSET,
metadata: AgentMetadata[AgentDepsT] | Unset = UNSET,
model_settings: (
AgentModelSettings[AgentDepsT] | Unset
) = UNSET,
spec: dict[str, Any] | AgentSpec | None = None
) -> Iterator[None]
Context manager to temporarily override agent name, dependencies, model, toolsets, tools, or instructions.
This is particularly useful when testing. You can find an example of this here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | Unset
|
The name to use instead of the name passed to the agent constructor and agent run. |
UNSET
|
deps
|
AgentDepsT | Unset
|
The dependencies to use instead of the dependencies passed to the agent run. |
UNSET
|
model
|
Model | KnownModelName | str | Unset
|
The model to use instead of the model passed to the agent run. |
UNSET
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | Unset
|
The toolsets to use instead of the toolsets passed to the agent constructor and agent run. |
UNSET
|
tools
|
Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | Unset
|
The tools to use instead of the tools registered with the agent. |
UNSET
|
instructions
|
AgentInstructions[AgentDepsT] | Unset
|
The instructions to use instead of the instructions registered with the agent. |
UNSET
|
metadata
|
AgentMetadata[AgentDepsT] | Unset
|
The metadata to use instead of the metadata passed to the agent constructor. When set, any
per-run |
UNSET
|
model_settings
|
AgentModelSettings[AgentDepsT] | Unset
|
The model settings to use instead of the model settings passed to the agent constructor.
When set, any per-run |
UNSET
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec providing defaults for override. Explicit params take precedence over spec values. |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 | |
instructions
instructions(
func: Callable[[RunContext[AgentDepsT]], str | None],
) -> Callable[[RunContext[AgentDepsT]], str | None]
instructions(
func: Callable[
[RunContext[AgentDepsT]], Awaitable[str | None]
],
) -> Callable[
[RunContext[AgentDepsT]], Awaitable[str | None]
]
instructions() -> Callable[
[SystemPromptFunc[AgentDepsT]],
SystemPromptFunc[AgentDepsT],
]
instructions(
func: SystemPromptFunc[AgentDepsT] | None = None,
) -> (
Callable[
[SystemPromptFunc[AgentDepsT]],
SystemPromptFunc[AgentDepsT],
]
| SystemPromptFunc[AgentDepsT]
)
Decorator to register an instructions function.
Optionally takes RunContext as its only argument.
Can decorate a sync or async functions.
The decorator can be used bare (agent.instructions).
Overloads for every possible signature of instructions are included so the decorator doesn't obscure
the type of the function.
Example:
from pydantic_ai import Agent, RunContext
agent = Agent('test', deps_type=str)
@agent.instructions
def simple_instructions() -> str:
return 'foobar'
@agent.instructions
async def async_instructions(ctx: RunContext[str]) -> str:
return f'{ctx.deps} is the best'
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 | |
system_prompt
system_prompt(
func: Callable[[RunContext[AgentDepsT]], str | None],
) -> Callable[[RunContext[AgentDepsT]], str | None]
system_prompt(
func: Callable[
[RunContext[AgentDepsT]], Awaitable[str | None]
],
) -> Callable[
[RunContext[AgentDepsT]], Awaitable[str | None]
]
system_prompt(*, dynamic: bool = False) -> Callable[
[SystemPromptFunc[AgentDepsT]],
SystemPromptFunc[AgentDepsT],
]
system_prompt(
func: SystemPromptFunc[AgentDepsT] | None = None,
/,
*,
dynamic: bool = False,
) -> (
Callable[
[SystemPromptFunc[AgentDepsT]],
SystemPromptFunc[AgentDepsT],
]
| SystemPromptFunc[AgentDepsT]
)
Decorator to register a system prompt function.
Optionally takes RunContext as its only argument.
Can decorate a sync or async functions.
The decorator can be used either bare (agent.system_prompt) or as a function call
(agent.system_prompt(...)), see the examples below.
Overloads for every possible signature of system_prompt are included so the decorator doesn't obscure
the type of the function, see tests/typed_agent.py for tests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
SystemPromptFunc[AgentDepsT] | None
|
The function to decorate |
None
|
dynamic
|
bool
|
If True, the system prompt will be reevaluated even when |
False
|
Example:
from pydantic_ai import Agent, RunContext
agent = Agent('test', deps_type=str)
@agent.system_prompt
def simple_system_prompt() -> str:
return 'foobar'
@agent.system_prompt(dynamic=True)
async def async_system_prompt(ctx: RunContext[str]) -> str:
return f'{ctx.deps} is the best'
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 | |
output_validator
output_validator(
func: Callable[
[RunContext[AgentDepsT], OutputDataT], OutputDataT
],
) -> Callable[
[RunContext[AgentDepsT], OutputDataT], OutputDataT
]
output_validator(
func: Callable[
[RunContext[AgentDepsT], OutputDataT],
Awaitable[OutputDataT],
],
) -> Callable[
[RunContext[AgentDepsT], OutputDataT],
Awaitable[OutputDataT],
]
output_validator(
func: Callable[[OutputDataT], OutputDataT],
) -> Callable[[OutputDataT], OutputDataT]
output_validator(
func: Callable[[OutputDataT], Awaitable[OutputDataT]],
) -> Callable[[OutputDataT], Awaitable[OutputDataT]]
output_validator(
func: OutputValidatorFunc[AgentDepsT, OutputDataT],
) -> OutputValidatorFunc[AgentDepsT, OutputDataT]
Decorator to register an output validator function.
Optionally takes RunContext as its first argument.
Can decorate a sync or async functions.
Overloads for every possible signature of output_validator are included so the decorator doesn't obscure
the type of the function, see tests/typed_agent.py for tests.
Example:
from pydantic_ai import Agent, ModelRetry, RunContext
agent = Agent('test', deps_type=str)
@agent.output_validator
def output_validator_simple(data: str) -> str:
if 'wrong' in data:
raise ModelRetry('wrong response')
return data
@agent.output_validator
async def output_validator_deps(ctx: RunContext[str], data: str) -> str:
if ctx.deps in data:
raise ModelRetry('wrong response')
return data
result = agent.run_sync('foobar', deps='spam')
print(result.output)
#> success (no tool calls)
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 | |
tool
tool(
func: ToolFuncContext[AgentDepsT, ToolParams],
) -> ToolFuncContext[AgentDepsT, ToolParams]
tool(
*,
name: str | None = None,
description: str | None = None,
retries: int | None = None,
prepare: ToolPrepareFunc[AgentDepsT] | None = None,
args_validator: (
ArgsValidatorFunc[AgentDepsT, ToolParams] | None
) = None,
docstring_format: DocstringFormat = "auto",
require_parameter_descriptions: bool = False,
schema_generator: type[
GenerateJsonSchema
] = GenerateToolJsonSchema,
strict: bool | None = None,
sequential: bool = False,
requires_approval: bool = False,
metadata: dict[str, Any] | None = None,
timeout: float | None = None
) -> Callable[
[ToolFuncContext[AgentDepsT, ToolParams]],
ToolFuncContext[AgentDepsT, ToolParams],
]
tool(
func: (
ToolFuncContext[AgentDepsT, ToolParams] | None
) = None,
/,
*,
name: str | None = None,
description: str | None = None,
retries: int | None = None,
prepare: ToolPrepareFunc[AgentDepsT] | None = None,
args_validator: (
ArgsValidatorFunc[AgentDepsT, ToolParams] | None
) = None,
docstring_format: DocstringFormat = "auto",
require_parameter_descriptions: bool = False,
schema_generator: type[
GenerateJsonSchema
] = GenerateToolJsonSchema,
strict: bool | None = None,
sequential: bool = False,
requires_approval: bool = False,
metadata: dict[str, Any] | None = None,
timeout: float | None = None,
) -> Any
Decorator to register a tool function which takes RunContext as its first argument.
Can decorate a sync or async functions.
The docstring is inspected to extract both the tool description and description of each parameter, learn more.
We can't add overloads for every possible signature of tool, since the return type is a recursive union
so the signature of functions decorated with @agent.tool is obscured.
Example:
from pydantic_ai import Agent, RunContext
agent = Agent('test', deps_type=int)
@agent.tool
def foobar(ctx: RunContext[int], x: int) -> int:
return ctx.deps + x
@agent.tool(retries=2)
async def spam(ctx: RunContext[str], y: float) -> float:
return ctx.deps + y
result = agent.run_sync('foobar', deps=1)
print(result.output)
#> {"foobar":1,"spam":1.0}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
ToolFuncContext[AgentDepsT, ToolParams] | None
|
The tool function to register. |
None
|
name
|
str | None
|
The name of the tool, defaults to the function name. |
None
|
description
|
str | None
|
The description of the tool, defaults to the function docstring. |
None
|
retries
|
int | None
|
The number of retries to allow for this tool, defaults to the agent's default retries, which defaults to 1. |
None
|
prepare
|
ToolPrepareFunc[AgentDepsT] | None
|
custom method to prepare the tool definition for each step, return |
None
|
args_validator
|
ArgsValidatorFunc[AgentDepsT, ToolParams] | None
|
custom method to validate tool arguments after schema validation has passed,
before execution. The validator receives the already-validated and type-converted parameters,
with |
None
|
docstring_format
|
DocstringFormat
|
The format of the docstring, see |
'auto'
|
require_parameter_descriptions
|
bool
|
If True, raise an error if a parameter description is missing. Defaults to False. |
False
|
schema_generator
|
type[GenerateJsonSchema]
|
The JSON schema generator class to use for this tool. Defaults to |
GenerateToolJsonSchema
|
strict
|
bool | None
|
Whether to enforce JSON schema compliance (only affects OpenAI).
See |
None
|
sequential
|
bool
|
Whether the function requires a sequential/serial execution environment. Defaults to False. |
False
|
requires_approval
|
bool
|
Whether this tool requires human-in-the-loop approval. Defaults to False. See the tools documentation for more info. |
False
|
metadata
|
dict[str, Any] | None
|
Optional metadata for the tool. This is not sent to the model but can be used for filtering and tool behavior customization. |
None
|
timeout
|
float | None
|
Timeout in seconds for tool execution. If the tool takes longer, a retry prompt is returned to the model.
Overrides the agent-level |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 | |
tool_plain
tool_plain(
func: ToolFuncPlain[ToolParams],
) -> ToolFuncPlain[ToolParams]
tool_plain(
*,
name: str | None = None,
description: str | None = None,
retries: int | None = None,
prepare: ToolPrepareFunc[AgentDepsT] | None = None,
args_validator: (
ArgsValidatorFunc[AgentDepsT, ToolParams] | None
) = None,
docstring_format: DocstringFormat = "auto",
require_parameter_descriptions: bool = False,
schema_generator: type[
GenerateJsonSchema
] = GenerateToolJsonSchema,
strict: bool | None = None,
sequential: bool = False,
requires_approval: bool = False,
metadata: dict[str, Any] | None = None,
timeout: float | None = None
) -> Callable[
[ToolFuncPlain[ToolParams]], ToolFuncPlain[ToolParams]
]
tool_plain(
func: ToolFuncPlain[ToolParams] | None = None,
/,
*,
name: str | None = None,
description: str | None = None,
retries: int | None = None,
prepare: ToolPrepareFunc[AgentDepsT] | None = None,
args_validator: (
ArgsValidatorFunc[AgentDepsT, ToolParams] | None
) = None,
docstring_format: DocstringFormat = "auto",
require_parameter_descriptions: bool = False,
schema_generator: type[
GenerateJsonSchema
] = GenerateToolJsonSchema,
strict: bool | None = None,
sequential: bool = False,
requires_approval: bool = False,
metadata: dict[str, Any] | None = None,
timeout: float | None = None,
) -> Any
Decorator to register a tool function which DOES NOT take RunContext as an argument.
Can decorate a sync or async functions.
The docstring is inspected to extract both the tool description and description of each parameter, learn more.
We can't add overloads for every possible signature of tool, since the return type is a recursive union
so the signature of functions decorated with @agent.tool is obscured.
Example:
from pydantic_ai import Agent, RunContext
agent = Agent('test')
@agent.tool
def foobar(ctx: RunContext[int]) -> int:
return 123
@agent.tool(retries=2)
async def spam(ctx: RunContext[str]) -> float:
return 3.14
result = agent.run_sync('foobar', deps=1)
print(result.output)
#> {"foobar":123,"spam":3.14}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
ToolFuncPlain[ToolParams] | None
|
The tool function to register. |
None
|
name
|
str | None
|
The name of the tool, defaults to the function name. |
None
|
description
|
str | None
|
The description of the tool, defaults to the function docstring. |
None
|
retries
|
int | None
|
The number of retries to allow for this tool, defaults to the agent's default retries, which defaults to 1. |
None
|
prepare
|
ToolPrepareFunc[AgentDepsT] | None
|
custom method to prepare the tool definition for each step, return |
None
|
args_validator
|
ArgsValidatorFunc[AgentDepsT, ToolParams] | None
|
custom method to validate tool arguments after schema validation has passed,
before execution. The validator receives the already-validated and type-converted parameters,
with |
None
|
docstring_format
|
DocstringFormat
|
The format of the docstring, see |
'auto'
|
require_parameter_descriptions
|
bool
|
If True, raise an error if a parameter description is missing. Defaults to False. |
False
|
schema_generator
|
type[GenerateJsonSchema]
|
The JSON schema generator class to use for this tool. Defaults to |
GenerateToolJsonSchema
|
strict
|
bool | None
|
Whether to enforce JSON schema compliance (only affects OpenAI).
See |
None
|
sequential
|
bool
|
Whether the function requires a sequential/serial execution environment. Defaults to False. |
False
|
requires_approval
|
bool
|
Whether this tool requires human-in-the-loop approval. Defaults to False. See the tools documentation for more info. |
False
|
metadata
|
dict[str, Any] | None
|
Optional metadata for the tool. This is not sent to the model but can be used for filtering and tool behavior customization. |
None
|
timeout
|
float | None
|
Timeout in seconds for tool execution. If the tool takes longer, a retry prompt is returned to the model.
Overrides the agent-level |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 | |
toolset
toolset(
func: ToolsetFunc[AgentDepsT],
) -> ToolsetFunc[AgentDepsT]
toolset(
*, per_run_step: bool = True, id: str | None = None
) -> Callable[
[ToolsetFunc[AgentDepsT]], ToolsetFunc[AgentDepsT]
]
toolset(
func: ToolsetFunc[AgentDepsT] | None = None,
/,
*,
per_run_step: bool = True,
id: str | None = None,
) -> Any
Decorator to register a toolset function which takes RunContext as its only argument.
Can decorate a sync or async functions.
The decorator can be used bare (agent.toolset).
Example:
from pydantic_ai import AbstractToolset, Agent, FunctionToolset, RunContext
agent = Agent('test', deps_type=str)
@agent.toolset
async def simple_toolset(ctx: RunContext[str]) -> AbstractToolset[str]:
return FunctionToolset()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
ToolsetFunc[AgentDepsT] | None
|
The toolset function to register. |
None
|
per_run_step
|
bool
|
Whether to re-evaluate the toolset for each run step. Defaults to True. |
True
|
id
|
str | None
|
An optional unique ID for the dynamic toolset. Required for use with durable execution environments like Temporal, where the ID identifies the toolset's activities within the workflow. |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 | |
toolsets
property
toolsets: Sequence[AbstractToolset[AgentDepsT]]
All toolsets registered on the agent, including a function toolset holding tools that were registered on the agent directly.
Output tools are not included.
__aenter__
async
__aenter__() -> Self
Enter the agent context.
This will start all MCPServerStdios registered as toolsets so they are ready to be used.
This is a no-op if the agent has already been entered.
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 | |
set_mcp_sampling_model
set_mcp_sampling_model(
model: Model | KnownModelName | str | None = None,
) -> None
Set the sampling model on all MCP servers registered with the agent.
If no sampling model is provided, the agent's model will be used.
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 | |
to_web
to_web(
*,
models: ModelsParam = None,
builtin_tools: list[AbstractBuiltinTool] | None = None,
deps: AgentDepsT = None,
model_settings: ModelSettings | None = None,
instructions: str | None = None,
html_source: str | Path | None = None
) -> Starlette
Create a Starlette app that serves a web chat UI for this agent.
This method returns a pre-configured Starlette application that provides a web-based chat interface for interacting with the agent. By default, the UI is fetched from a CDN and cached on first use.
The returned Starlette application can be mounted into a FastAPI app or run directly with any ASGI server (uvicorn, hypercorn, etc.).
Note that the deps and model_settings will be the same for each request.
To provide different deps for each request use the lower-level adapters directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
ModelsParam
|
Additional models to make available in the UI. Can be:
- A sequence of model names/instances (e.g., |
None
|
builtin_tools
|
list[AbstractBuiltinTool] | None
|
Additional builtin tools to make available in the UI.
The agent's configured builtin tools are always included. Tool labels
in the UI are derived from the tool's |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for all requests. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for all model requests. |
None
|
instructions
|
str | None
|
Optional extra instructions to pass to each agent run. |
None
|
html_source
|
str | Path | None
|
Path or URL for the chat UI HTML. Can be: - None (default): Fetches from CDN and caches locally - A Path instance: Reads from the local file - A URL string (http:// or https://): Fetches from the URL - A file path string: Reads from the local file |
None
|
Returns:
| Type | Description |
|---|---|
Starlette
|
A configured Starlette application ready to be served (e.g., with uvicorn) |
Example
from pydantic_ai import Agent
from pydantic_ai.builtin_tools import WebSearchTool
agent = Agent('openai:gpt-5', builtin_tools=[WebSearchTool()])
# Simple usage - uses agent's model and builtin tools
app = agent.to_web()
# Or provide additional models for UI selection
app = agent.to_web(models=['openai:gpt-5', 'anthropic:claude-sonnet-4-6'])
# Then run with: uvicorn app:app --reload
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 | |
run_mcp_servers
async
deprecated
run_mcp_servers(
model: Model | KnownModelName | str | None = None,
) -> AsyncIterator[None]
Deprecated
run_mcp_servers is deprecated, use async with agent: instead. If you need to set a sampling model on all MCP servers, use agent.set_mcp_sampling_model().
Run MCPServerStdios so they can be used by the agent.
Deprecated: use async with agent instead.
If you need to set a sampling model on all MCP servers, use agent.set_mcp_sampling_model().
Returns: a context manager to start and shutdown the servers.
Source code in pydantic_ai_slim/pydantic_ai/agent/__init__.py
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 | |
AbstractAgent
Bases: Generic[AgentDepsT, OutputDataT], ABC
Abstract superclass for Agent, WrapperAgent, and your own custom agent implementations.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 | |
model
abstractmethod
property
model: Model | KnownModelName | str | None
The default model configured for this agent.
name
abstractmethod
property
writable
name: str | None
The name of the agent, used for logging.
If None, we try to infer the agent name from the call frame when the agent is first run.
description
abstractmethod
property
writable
description: str | None
A human-readable description of the agent.
output_type
abstractmethod
property
output_type: OutputSpec[OutputDataT]
The type of data output by agent runs, used to validate the data returned by the model, defaults to str.
event_stream_handler
abstractmethod
property
event_stream_handler: EventStreamHandler[AgentDepsT] | None
Optional handler for events from the model's streaming response and the agent's execution of tools.
toolsets
abstractmethod
property
toolsets: Sequence[AbstractToolset[AgentDepsT]]
All toolsets registered on the agent.
Output tools are not included.
output_json_schema
output_json_schema(
output_type: (
OutputSpec[OutputDataT | RunOutputDataT] | None
) = None,
) -> JsonSchema
The output return JSON schema.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
run
async
run(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AgentRunResult[OutputDataT]
run(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AgentRunResult[RunOutputDataT]
run(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AgentRunResult[Any]
Run the agent with a user prompt in async mode.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then runs the graph to completion. The result of the run is returned.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
agent_run = await agent.run('What is the capital of France?')
print(agent_run.output)
#> The capital of France is Paris.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
event_stream_handler
|
EventStreamHandler[AgentDepsT] | None
|
Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
AgentRunResult[Any]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
run_sync
run_sync(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AgentRunResult[OutputDataT]
run_sync(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AgentRunResult[RunOutputDataT]
run_sync(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AgentRunResult[Any]
Synchronously run the agent with a user prompt.
This is a convenience method that wraps self.run with loop.run_until_complete(...).
You therefore can't use this method inside async code or if there's an active event loop.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
result_sync = agent.run_sync('What is the capital of Italy?')
print(result_sync.output)
#> The capital of Italy is Rome.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
event_stream_handler
|
EventStreamHandler[AgentDepsT] | None
|
Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
AgentRunResult[Any]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
run_stream
async
run_stream(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
StreamedRunResult[AgentDepsT, OutputDataT]
]
run_stream(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
StreamedRunResult[AgentDepsT, RunOutputDataT]
]
run_stream(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[StreamedRunResult[AgentDepsT, Any]]
Run the agent with a user prompt in async streaming mode.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then
runs the graph until the model produces output matching the output_type, for example text or structured data.
At this point, a streaming run result object is yielded from which you can stream the output as it comes in,
and -- once this output has completed streaming -- get the complete output, message history, and usage.
As this method will consider the first output matching the output_type to be the final output,
it will stop running the agent graph and will not execute any tool calls made by the model after this "final" output.
If you want to always run the agent graph to completion and stream events and output at the same time,
use agent.run() with an event_stream_handler or agent.iter() instead.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
async with agent.run_stream('What is the capital of the UK?') as response:
print(await response.get_output())
#> The capital of the UK is London.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
event_stream_handler
|
EventStreamHandler[AgentDepsT] | None
|
Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run. It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager. Note that it does not receive any events after the final result is found. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[StreamedRunResult[AgentDepsT, Any]]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 | |
run_stream_sync
run_stream_sync(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> StreamedRunResultSync[AgentDepsT, OutputDataT]
run_stream_sync(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[AbstractBuiltinTool] | None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> StreamedRunResultSync[AgentDepsT, RunOutputDataT]
run_stream_sync(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
event_stream_handler: (
EventStreamHandler[AgentDepsT] | None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> StreamedRunResultSync[AgentDepsT, Any]
Run the agent with a user prompt in sync streaming mode.
This is a convenience method that wraps run_stream() with loop.run_until_complete(...).
You therefore can't use this method inside async code or if there's an active event loop.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then
runs the graph until the model produces output matching the output_type, for example text or structured data.
At this point, a streaming run result object is yielded from which you can stream the output as it comes in,
and -- once this output has completed streaming -- get the complete output, message history, and usage.
As this method will consider the first output matching the output_type to be the final output,
it will stop running the agent graph and will not execute any tool calls made by the model after this "final" output.
If you want to always run the agent graph to completion and stream events and output at the same time,
use agent.run() with an event_stream_handler or agent.iter() instead.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
def main():
response = agent.run_stream_sync('What is the capital of the UK?')
print(response.get_output())
#> The capital of the UK is London.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
event_stream_handler
|
EventStreamHandler[AgentDepsT] | None
|
Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run. It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager. Note that it does not receive any events after the final result is found. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
StreamedRunResultSync[AgentDepsT, Any]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 | |
run_stream_events
run_stream_events(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[
AgentStreamEvent | AgentRunResultEvent[OutputDataT]
]
run_stream_events(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[
AgentStreamEvent | AgentRunResultEvent[RunOutputDataT]
]
run_stream_events(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[
AgentStreamEvent | AgentRunResultEvent[Any]
]
Run the agent with a user prompt in async mode and stream events from the run.
This is a convenience method that wraps self.run and
uses the event_stream_handler kwarg to get a stream of events from the run.
Example:
from pydantic_ai import Agent, AgentRunResultEvent, AgentStreamEvent
agent = Agent('openai:gpt-5.2')
async def main():
events: list[AgentStreamEvent | AgentRunResultEvent] = []
async for event in agent.run_stream_events('What is the capital of France?'):
events.append(event)
print(events)
'''
[
PartStartEvent(index=0, part=TextPart(content='The capital of ')),
FinalResultEvent(tool_name=None, tool_call_id=None),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
PartEndEvent(
index=0, part=TextPart(content='The capital of France is Paris. ')
),
AgentRunResultEvent(
result=AgentRunResult(output='The capital of France is Paris. ')
),
]
'''
Arguments are the same as for self.run,
except that event_stream_handler is now allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[AgentStreamEvent | AgentRunResultEvent[Any]]
|
An async iterable of stream events |
AsyncIterator[AgentStreamEvent | AgentRunResultEvent[Any]]
|
run result. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 | |
iter
abstractmethod
async
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
AgentRun[AgentDepsT, OutputDataT]
]
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
AgentRun[AgentDepsT, RunOutputDataT]
]
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[AgentRun[AgentDepsT, Any]]
A contextmanager which can be used to iterate over the agent graph's nodes as they are executed.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
AgentRun object. The AgentRun can be used to async-iterate over the nodes of the graph as they are
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
stream of events coming from the execution of tools.
The AgentRun also provides methods to access the full message history, new messages, and usage statistics,
and the final result of the run once it has completed.
For more details, see the documentation of AgentRun.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print(agent_run.result.output)
#> The capital of France is Paris.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request, or a callable
that receives |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. Accepts a dictionary or a callable taking
|
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. At run time, spec values are additive. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[AgentRun[AgentDepsT, Any]]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 | |
override
abstractmethod
override(
*,
name: str | Unset = UNSET,
deps: AgentDepsT | Unset = UNSET,
model: Model | KnownModelName | str | Unset = UNSET,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | Unset
) = UNSET,
tools: (
Sequence[
Tool[AgentDepsT]
| ToolFuncEither[AgentDepsT, ...]
]
| Unset
) = UNSET,
instructions: (
AgentInstructions[AgentDepsT] | Unset
) = UNSET,
model_settings: (
AgentModelSettings[AgentDepsT] | Unset
) = UNSET,
spec: dict[str, Any] | AgentSpec | None = None
) -> Iterator[None]
Context manager to temporarily override agent name, dependencies, model, toolsets, tools, or instructions.
This is particularly useful when testing. You can find an example of this here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | Unset
|
The name to use instead of the name passed to the agent constructor and agent run. |
UNSET
|
deps
|
AgentDepsT | Unset
|
The dependencies to use instead of the dependencies passed to the agent run. |
UNSET
|
model
|
Model | KnownModelName | str | Unset
|
The model to use instead of the model passed to the agent run. |
UNSET
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | Unset
|
The toolsets to use instead of the toolsets passed to the agent constructor and agent run. |
UNSET
|
tools
|
Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | Unset
|
The tools to use instead of the tools registered with the agent. |
UNSET
|
instructions
|
AgentInstructions[AgentDepsT] | Unset
|
The instructions to use instead of the instructions registered with the agent. |
UNSET
|
model_settings
|
AgentModelSettings[AgentDepsT] | Unset
|
The model settings to use instead of the model settings passed to the agent constructor.
When set, any per-run |
UNSET
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec providing defaults for override. |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 | |
parallel_tool_call_execution_mode
staticmethod
parallel_tool_call_execution_mode(
mode: ParallelExecutionMode = "parallel",
) -> Iterator[None]
Set the parallel execution mode during the context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
ParallelExecutionMode
|
The execution mode for tool calls: - 'parallel': Run tool calls in parallel, yielding events as they complete (default). - 'sequential': Run tool calls one at a time in order. - 'parallel_ordered_events': Run tool calls in parallel, but events are emitted in order, after all calls complete. |
'parallel'
|
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 | |
sequential_tool_calls
deprecated
staticmethod
sequential_tool_calls() -> Iterator[None]
Deprecated
Use parallel_execution_mode("sequential") instead.
Run tool calls sequentially during the context.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1253 1254 1255 1256 1257 1258 1259 | |
is_model_request_node
staticmethod
is_model_request_node(
node: AgentNode[T, S] | End[FinalResult[S]],
) -> TypeIs[ModelRequestNode[T, S]]
Check if the node is a ModelRequestNode, narrowing the type if it is.
This method preserves the generic parameters while narrowing the type, unlike a direct call to isinstance.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1261 1262 1263 1264 1265 1266 1267 1268 1269 | |
is_call_tools_node
staticmethod
Check if the node is a CallToolsNode, narrowing the type if it is.
This method preserves the generic parameters while narrowing the type, unlike a direct call to isinstance.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1271 1272 1273 1274 1275 1276 1277 1278 1279 | |
is_user_prompt_node
staticmethod
Check if the node is a UserPromptNode, narrowing the type if it is.
This method preserves the generic parameters while narrowing the type, unlike a direct call to isinstance.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1281 1282 1283 1284 1285 1286 1287 1288 1289 | |
is_end_node
staticmethod
Check if the node is a End, narrowing the type if it is.
This method preserves the generic parameters while narrowing the type, unlike a direct call to isinstance.
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1291 1292 1293 1294 1295 1296 1297 1298 1299 | |
to_ag_ui
to_ag_ui(
*,
output_type: OutputSpec[OutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
deps: AgentDepsT = None,
model_settings: ModelSettings | None = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
debug: bool = False,
routes: Sequence[BaseRoute] | None = None,
middleware: Sequence[Middleware] | None = None,
exception_handlers: (
Mapping[Any, ExceptionHandler] | None
) = None,
on_startup: Sequence[Callable[[], Any]] | None = None,
on_shutdown: Sequence[Callable[[], Any]] | None = None,
lifespan: (
Lifespan[AGUIApp[AgentDepsT, OutputDataT]] | None
) = None
) -> AGUIApp[AgentDepsT, OutputDataT]
Returns an ASGI application that handles every AG-UI request by running the agent.
Note that the deps will be the same for each request, with the exception of the AG-UI state that's
injected into the state field of a deps object that implements the StateHandler protocol.
To provide different deps for each request (e.g. based on the authenticated user),
use pydantic_ai.ag_ui.run_ag_ui or
pydantic_ai.ag_ui.handle_ag_ui_request instead.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
app = agent.to_ag_ui()
The app is an ASGI application that can be used with any ASGI server.
To run the application, you can use the following command:
uvicorn app:app --host 0.0.0.0 --port 8000
See AG-UI docs for more information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_type
|
OutputSpec[OutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
debug
|
bool
|
Boolean indicating if debug tracebacks should be returned on errors. |
False
|
routes
|
Sequence[BaseRoute] | None
|
A list of routes to serve incoming HTTP and WebSocket requests. |
None
|
middleware
|
Sequence[Middleware] | None
|
A list of middleware to run for every request. A starlette application will always
automatically include two middleware classes. |
None
|
exception_handlers
|
Mapping[Any, ExceptionHandler] | None
|
A mapping of either integer status codes, or exception class types onto
callables which handle the exceptions. Exception handler callables should be of the form
|
None
|
on_startup
|
Sequence[Callable[[], Any]] | None
|
A list of callables to run on application startup. Startup handler callables do not take any arguments, and may be either standard functions, or async functions. |
None
|
on_shutdown
|
Sequence[Callable[[], Any]] | None
|
A list of callables to run on application shutdown. Shutdown handler callables do not take any arguments, and may be either standard functions, or async functions. |
None
|
lifespan
|
Lifespan[AGUIApp[AgentDepsT, OutputDataT]] | None
|
A lifespan context function, which can be used to perform startup and shutdown tasks.
This is a newer style that replaces the |
None
|
Returns:
| Type | Description |
|---|---|
AGUIApp[AgentDepsT, OutputDataT]
|
An ASGI application for running Pydantic AI agents with AG-UI protocol support. |
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 | |
to_a2a
to_a2a(
*,
storage: Storage | None = None,
broker: Broker | None = None,
name: str | None = None,
url: str = "http://localhost:8000",
version: str = "1.0.0",
description: str | None = None,
provider: AgentProvider | None = None,
skills: list[Skill] | None = None,
debug: bool = False,
routes: Sequence[Route] | None = None,
middleware: Sequence[Middleware] | None = None,
exception_handlers: (
dict[Any, ExceptionHandler] | None
) = None,
lifespan: Lifespan[FastA2A] | None = None
) -> FastA2A
Convert the agent to a FastA2A application.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
app = agent.to_a2a()
The app is an ASGI application that can be used with any ASGI server.
To run the application, you can use the following command:
uvicorn app:app --host 0.0.0.0 --port 8000
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 | |
to_cli
async
to_cli(
deps: AgentDepsT = None,
prog_name: str = "pydantic-ai",
message_history: Sequence[ModelMessage] | None = None,
model_settings: ModelSettings | None = None,
usage_limits: UsageLimits | None = None,
) -> None
Run the agent in a CLI chat interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deps
|
AgentDepsT
|
The dependencies to pass to the agent. |
None
|
prog_name
|
str
|
The name of the program to use for the CLI. Defaults to 'pydantic-ai'. |
'pydantic-ai'
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2', instructions='You always respond in Italian.')
async def main():
await agent.to_cli()
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 | |
to_cli_sync
to_cli_sync(
deps: AgentDepsT = None,
prog_name: str = "pydantic-ai",
message_history: Sequence[ModelMessage] | None = None,
model_settings: ModelSettings | None = None,
usage_limits: UsageLimits | None = None,
) -> None
Run the agent in a CLI chat interface with the non-async interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deps
|
AgentDepsT
|
The dependencies to pass to the agent. |
None
|
prog_name
|
str
|
The name of the program to use for the CLI. Defaults to 'pydantic-ai'. |
'pydantic-ai'
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
model_settings
|
ModelSettings | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2', instructions='You always respond in Italian.')
agent.to_cli_sync()
agent.to_cli_sync(prog_name='assistant')
Source code in pydantic_ai_slim/pydantic_ai/agent/abstract.py
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 | |
WrapperAgent
Bases: AbstractAgent[AgentDepsT, OutputDataT]
Agent which wraps another agent.
Does nothing on its own, used as a base class.
Source code in pydantic_ai_slim/pydantic_ai/agent/wrapper.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
iter
async
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
AgentRun[AgentDepsT, OutputDataT]
]
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT],
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AbstractAsyncContextManager[
AgentRun[AgentDepsT, RunOutputDataT]
]
iter(
user_prompt: str | Sequence[UserContent] | None = None,
*,
output_type: OutputSpec[RunOutputDataT] | None = None,
message_history: Sequence[ModelMessage] | None = None,
deferred_tool_results: (
DeferredToolResults | None
) = None,
model: Model | KnownModelName | str | None = None,
instructions: AgentInstructions[AgentDepsT] = None,
deps: AgentDepsT = None,
model_settings: (
AgentModelSettings[AgentDepsT] | None
) = None,
usage_limits: UsageLimits | None = None,
usage: RunUsage | None = None,
metadata: AgentMetadata[AgentDepsT] | None = None,
infer_name: bool = True,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | None
) = None,
builtin_tools: (
Sequence[
AbstractBuiltinTool
| BuiltinToolFunc[AgentDepsT]
]
| None
) = None,
spec: dict[str, Any] | AgentSpec | None = None
) -> AsyncIterator[AgentRun[AgentDepsT, Any]]
A contextmanager which can be used to iterate over the agent graph's nodes as they are executed.
This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
AgentRun object. The AgentRun can be used to async-iterate over the nodes of the graph as they are
executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
stream of events coming from the execution of tools.
The AgentRun also provides methods to access the full message history, new messages, and usage statistics,
and the final result of the run once it has completed.
For more details, see the documentation of AgentRun.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print(agent_run.result.output)
#> The capital of France is Paris.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str | Sequence[UserContent] | None
|
User input to start/continue the conversation. |
None
|
output_type
|
OutputSpec[RunOutputDataT] | None
|
Custom output type to use for this run, |
None
|
message_history
|
Sequence[ModelMessage] | None
|
History of the conversation so far. |
None
|
deferred_tool_results
|
DeferredToolResults | None
|
Optional results for deferred tool calls in the message history. |
None
|
model
|
Model | KnownModelName | str | None
|
Optional model to use for this run, required if |
None
|
instructions
|
AgentInstructions[AgentDepsT]
|
Optional additional instructions to use for this run. |
None
|
deps
|
AgentDepsT
|
Optional dependencies to use for this run. |
None
|
model_settings
|
AgentModelSettings[AgentDepsT] | None
|
Optional settings to use for this model's request. |
None
|
usage_limits
|
UsageLimits | None
|
Optional limits on model request count or token usage. |
None
|
usage
|
RunUsage | None
|
Optional usage to start with, useful for resuming a conversation or agents used in tools. |
None
|
metadata
|
AgentMetadata[AgentDepsT] | None
|
Optional metadata to attach to this run. |
None
|
infer_name
|
bool
|
Whether to try to infer the agent name from the call frame if it's not set. |
True
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | None
|
Optional additional toolsets for this run. |
None
|
builtin_tools
|
Sequence[AbstractBuiltinTool | BuiltinToolFunc[AgentDepsT]] | None
|
Optional additional builtin tools for this run. |
None
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply for this run. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[AgentRun[AgentDepsT, Any]]
|
The result of the run. |
Source code in pydantic_ai_slim/pydantic_ai/agent/wrapper.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
override
override(
*,
name: str | Unset = UNSET,
deps: AgentDepsT | Unset = UNSET,
model: Model | KnownModelName | str | Unset = UNSET,
toolsets: (
Sequence[AbstractToolset[AgentDepsT]] | Unset
) = UNSET,
tools: (
Sequence[
Tool[AgentDepsT]
| ToolFuncEither[AgentDepsT, ...]
]
| Unset
) = UNSET,
instructions: (
AgentInstructions[AgentDepsT] | Unset
) = UNSET,
model_settings: (
AgentModelSettings[AgentDepsT] | Unset
) = UNSET,
spec: dict[str, Any] | AgentSpec | None = None
) -> Iterator[None]
Context manager to temporarily override agent name, dependencies, model, toolsets, tools, or instructions.
This is particularly useful when testing. You can find an example of this here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | Unset
|
The name to use instead of the name passed to the agent constructor and agent run. |
UNSET
|
deps
|
AgentDepsT | Unset
|
The dependencies to use instead of the dependencies passed to the agent run. |
UNSET
|
model
|
Model | KnownModelName | str | Unset
|
The model to use instead of the model passed to the agent run. |
UNSET
|
toolsets
|
Sequence[AbstractToolset[AgentDepsT]] | Unset
|
The toolsets to use instead of the toolsets passed to the agent constructor and agent run. |
UNSET
|
tools
|
Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | Unset
|
The tools to use instead of the tools registered with the agent. |
UNSET
|
instructions
|
AgentInstructions[AgentDepsT] | Unset
|
The instructions to use instead of the instructions registered with the agent. |
UNSET
|
model_settings
|
AgentModelSettings[AgentDepsT] | Unset
|
The model settings to use instead of the model settings passed to the agent constructor.
When set, any per-run |
UNSET
|
spec
|
dict[str, Any] | AgentSpec | None
|
Optional agent spec to apply as overrides. |
None
|
Source code in pydantic_ai_slim/pydantic_ai/agent/wrapper.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
AgentRun
dataclass
Bases: Generic[AgentDepsT, OutputDataT]
A stateful, async-iterable run of an Agent.
You generally obtain an AgentRun instance by calling async with my_agent.iter(...) as agent_run:.
Once you have an instance, you can use it to iterate through the run's nodes as they execute. When an
End is reached, the run finishes and result
becomes available.
Example:
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
async def main():
nodes = []
# Iterate through the run, recording each node along the way:
async with agent.iter('What is the capital of France?') as agent_run:
async for node in agent_run:
nodes.append(node)
print(nodes)
'''
[
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print(agent_run.result.output)
#> The capital of France is Paris.
You can also manually drive the iteration using the next method for
more granular control.
Source code in pydantic_ai_slim/pydantic_ai/run.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
ctx
property
ctx: GraphRunContext[
GraphAgentState, GraphAgentDeps[AgentDepsT, Any]
]
The current context of the agent run.
next_node
property
next_node: (
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
)
The next node that will be run in the agent graph.
This is the next node that will be used during async iteration, or if a node is not passed to self.next(...).
result
property
result: AgentRunResult[OutputDataT] | None
The final result of the run if it has ended, otherwise None.
Once the run returns an End node, result is populated
with an AgentRunResult.
all_messages
all_messages() -> list[ModelMessage]
Return all messages for the run so far.
Messages from older runs are included.
Source code in pydantic_ai_slim/pydantic_ai/run.py
139 140 141 142 143 144 | |
all_messages_json
Return all messages from all_messages as JSON bytes.
Returns:
| Type | Description |
|---|---|
bytes
|
JSON bytes representing the messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
146 147 148 149 150 151 152 | |
new_messages
new_messages() -> list[ModelMessage]
Return new messages for the run so far.
Messages from older runs are excluded.
Source code in pydantic_ai_slim/pydantic_ai/run.py
154 155 156 157 158 159 | |
new_messages_json
new_messages_json() -> bytes
Return new messages from new_messages as JSON bytes.
Returns:
| Type | Description |
|---|---|
bytes
|
JSON bytes representing the new messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
161 162 163 164 165 166 167 | |
__aiter__
__aiter__() -> (
AsyncIterator[
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
]
)
Provide async-iteration over the nodes in the agent run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
169 170 171 172 173 | |
__anext__
async
__anext__() -> (
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
)
Advance to the next node automatically based on the last returned node.
Source code in pydantic_ai_slim/pydantic_ai/run.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
next
async
next(
node: AgentNode[AgentDepsT, OutputDataT],
) -> (
AgentNode[AgentDepsT, OutputDataT]
| End[FinalResult[OutputDataT]]
)
Manually drive the agent run by passing in the node you want to run next.
This lets you inspect or mutate the node before continuing execution, or skip certain nodes
under dynamic conditions. The agent run should be stopped when you return an End
node.
Example:
from pydantic_ai import Agent
from pydantic_graph import End
agent = Agent('openai:gpt-5.2')
async def main():
async with agent.iter('What is the capital of France?') as agent_run:
next_node = agent_run.next_node # start with the first node
nodes = [next_node]
while not isinstance(next_node, End):
next_node = await agent_run.next(next_node)
nodes.append(next_node)
# Once `next_node` is an End, we've finished:
print(nodes)
'''
[
UserPromptNode(
user_prompt='What is the capital of France?',
instructions_functions=[],
system_prompts=(),
system_prompt_functions=[],
system_prompt_dynamic_functions={},
),
ModelRequestNode(
request=ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=datetime.datetime(...),
)
],
timestamp=datetime.datetime(...),
run_id='...',
)
),
CallToolsNode(
model_response=ModelResponse(
parts=[TextPart(content='The capital of France is Paris.')],
usage=RequestUsage(input_tokens=56, output_tokens=7),
model_name='gpt-5.2',
timestamp=datetime.datetime(...),
run_id='...',
)
),
End(data=FinalResult(output='The capital of France is Paris.')),
]
'''
print('Final result:', agent_run.result.output)
#> Final result: The capital of France is Paris.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
AgentNode[AgentDepsT, OutputDataT]
|
The node to run next in the graph. |
required |
Returns:
| Type | Description |
|---|---|
AgentNode[AgentDepsT, OutputDataT] | End[FinalResult[OutputDataT]]
|
The next node returned by the graph logic, or an |
AgentNode[AgentDepsT, OutputDataT] | End[FinalResult[OutputDataT]]
|
the run has completed. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
usage
usage() -> RunUsage
Get usage statistics for the run so far, including token usage, model requests, and so on.
Source code in pydantic_ai_slim/pydantic_ai/run.py
299 300 301 | |
metadata
property
Metadata associated with this agent run, if configured.
AgentRunResult
dataclass
Bases: Generic[OutputDataT]
The final result of an agent run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | |
all_messages
all_messages(
*, output_tool_return_content: str | None = None
) -> list[ModelMessage]
Return the history of _messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
| Type | Description |
|---|---|
list[ModelMessage]
|
List of messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | |
all_messages_json
Return all messages from all_messages as JSON bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
| Type | Description |
|---|---|
bytes
|
JSON bytes representing the messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | |
new_messages
new_messages(
*, output_tool_return_content: str | None = None
) -> list[ModelMessage]
Return new messages associated with this run.
Messages from older runs are excluded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
| Type | Description |
|---|---|
list[ModelMessage]
|
List of new messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
new_messages_json
Return new messages from new_messages as JSON bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_tool_return_content
|
str | None
|
The return content of the tool call to set in the last message.
This provides a convenient way to modify the content of the output tool call if you want to continue
the conversation and want to set the response to the output tool call. If |
None
|
Returns:
| Type | Description |
|---|---|
bytes
|
JSON bytes representing the new messages. |
Source code in pydantic_ai_slim/pydantic_ai/run.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | |
usage
usage() -> RunUsage
Return the usage of the whole run.
Source code in pydantic_ai_slim/pydantic_ai/run.py
438 439 440 | |
timestamp
timestamp() -> datetime
Return the timestamp of last response.
Source code in pydantic_ai_slim/pydantic_ai/run.py
443 444 445 | |
metadata
property
Metadata associated with this agent run, if configured.
RunOutputDataT
module-attribute
RunOutputDataT = TypeVar('RunOutputDataT')
Type variable for the result data of a run where output_type was customized on the run call.
capture_run_messages
capture_run_messages() -> Iterator[list[ModelMessage]]
Context manager to access the messages used in a run, run_sync, or run_stream call.
Useful when a run may raise an exception, see model errors for more information.
Examples:
from pydantic_ai import Agent, capture_run_messages
agent = Agent('test')
with capture_run_messages() as messages:
try:
result = agent.run_sync('foobar')
except Exception:
print(messages)
raise
Note
If you call run, run_sync, or run_stream more than once within a single capture_run_messages context,
messages will represent the messages exchanged during the first call only.
Source code in pydantic_ai_slim/pydantic_ai/_agent_graph.py
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 | |
InstrumentationSettings
dataclass
Options for instrumenting models and agents with OpenTelemetry.
Used in:
Agent(instrument=...)Agent.instrument_all()InstrumentedModel
See the Debugging and Monitoring guide for more info.
Source code in pydantic_ai_slim/pydantic_ai/models/instrumented.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | |
__init__
__init__(
*,
tracer_provider: TracerProvider | None = None,
meter_provider: MeterProvider | None = None,
include_binary_content: bool = True,
include_content: bool = True,
version: Literal[
1, 2, 3, 4
] = DEFAULT_INSTRUMENTATION_VERSION,
event_mode: Literal[
"attributes", "logs"
] = "attributes",
logger_provider: LoggerProvider | None = None,
use_aggregated_usage_attribute_names: bool = False
)
Create instrumentation options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracer_provider
|
TracerProvider | None
|
The OpenTelemetry tracer provider to use.
If not provided, the global tracer provider is used.
Calling |
None
|
meter_provider
|
MeterProvider | None
|
The OpenTelemetry meter provider to use.
If not provided, the global meter provider is used.
Calling |
None
|
include_binary_content
|
bool
|
Whether to include binary content in the instrumentation events. |
True
|
include_content
|
bool
|
Whether to include prompts, completions, and tool call arguments and responses in the instrumentation events. |
True
|
version
|
Literal[1, 2, 3, 4]
|
Version of the data format. This is unrelated to the Pydantic AI package version.
Version 1 is based on the legacy event-based OpenTelemetry GenAI spec
and will be removed in a future release.
The parameters |
DEFAULT_INSTRUMENTATION_VERSION
|
event_mode
|
Literal['attributes', 'logs']
|
The mode for emitting events in version 1.
If |
'attributes'
|
logger_provider
|
LoggerProvider | None
|
The OpenTelemetry logger provider to use.
If not provided, the global logger provider is used.
Calling |
None
|
use_aggregated_usage_attribute_names
|
bool
|
Whether to use |
False
|
Source code in pydantic_ai_slim/pydantic_ai/models/instrumented.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | |
messages_to_otel_events
messages_to_otel_events(
messages: list[ModelMessage],
parameters: ModelRequestParameters | None = None,
) -> list[LogRecord]
Convert a list of model messages to OpenTelemetry events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ModelMessage]
|
The messages to convert. |
required |
parameters
|
ModelRequestParameters | None
|
The model request parameters. |
None
|
Returns:
| Type | Description |
|---|---|
list[LogRecord]
|
A list of OpenTelemetry events. |
Source code in pydantic_ai_slim/pydantic_ai/models/instrumented.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
EventStreamHandler
module-attribute
EventStreamHandler: TypeAlias = Callable[
[
RunContext[AgentDepsT],
AsyncIterable[AgentStreamEvent],
],
Awaitable[None],
]
A function that receives agent RunContext and an async iterable of events from the model's streaming response and the agent's execution of tools.