Skip to content

Commit ac888f8

Browse files
authored
Merge branch 'main' into docs/add-examples-badge
2 parents 55b7315 + 35dbfa1 commit ac888f8

File tree

4 files changed

+98
-17
lines changed

4 files changed

+98
-17
lines changed

README.md

Lines changed: 89 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,35 +11,77 @@ Official SDK from [WorkflowAI](https://workflowai.com) for Python.
1111

1212
This SDK is designed for Python teams who prefer code-first development. It provides greater control through direct code integration while still leveraging the full power of the WorkflowAI platform, complementing the web-app experience.
1313

14+
#### Try in CursorAI:
15+
```
16+
install `pip workflowai` and from https://docs.workflowai.com/python-sdk/agent build an agent that [add description of the agent you want to build]
17+
```
18+
19+
https://github.com/user-attachments/assets/634c1100-f354-46bc-9aee-92c3f2044cd6
20+
1421
## Key Features
1522

16-
- **Model-agnostic**: Works with all major AI models including OpenAI, Anthropic, Claude, Google/Gemini, Mistral, Deepseek, with a unified interface that makes switching between providers seamless. [View all supported models](https://github.com/WorkflowAI/python-sdk/blob/main/workflowai/core/domain/model.py).
23+
- **Model-agnostic**: Works with all major AI models including OpenAI, Anthropic, Claude, Google/Gemini, Mistral, DeepSeek, Grok with a unified interface that makes switching between providers seamless. [View all supported models](https://github.com/WorkflowAI/python-sdk/blob/main/workflowai/core/domain/model.py).
24+
25+
https://github.com/user-attachments/assets/7259adee-1152-44a4-9a15-78fc0a5935e1
1726

1827
- **Open-source and flexible deployment**: WorkflowAI is fully open-source with flexible deployment options. Run it self-hosted on your own infrastructure for maximum data control, or use the managed [WorkflowAI Cloud](https://docs.workflowai.com/workflowai-cloud/introduction) service for hassle-free updates and automatic scaling.
1928

20-
- **Observability integrated**: Built-in monitoring and logging capabilities that provide insights into your AI workflows, making debugging and optimization straightforward. Learn more about [observability features](https://docs.workflowai.com/concepts/runs).
29+
- **Structured output**: Uses Pydantic models to validate and structure AI responses. WorkflowAI ensures your AI responses always match your defined structure, simplifying integrations, reducing parsing errors, and making your data reliable and ready to use. Learn more about [structured input and output](https://docs.workflowai.com/python-sdk/agent#schema-input-output).
2130

22-
- **Cost tracking**: Automatically calculates and tracks the cost of each AI model run, providing transparency and helping you manage your AI budget effectively. Learn more about [cost tracking](https://docs.workflowai.com/python-sdk/agent#cost-latency).
31+
https://github.com/user-attachments/assets/0d05bf43-abdb-48fa-b96f-a6c8917c5479
2332

24-
- **Type-safe**: Leverages Python's type system to catch errors at development time rather than runtime, ensuring more reliable AI applications.
33+
- **Observability integrated**: Built-in monitoring and logging capabilities that provide insights into your AI workflows, making debugging and optimization straightforward. Learn more about [observability features](https://docs.workflowai.com/concepts/runs).
2534

26-
- **Structured output**: Uses Pydantic models to validate and structure AI responses. WorkflowAI ensures your AI responses always match your defined structure, simplifying integrations, reducing parsing errors, and making your data reliable and ready for use. Learn more about [structured input and output](https://docs.workflowai.com/python-sdk/agent#schema-input-output).
35+
https://github.com/user-attachments/assets/7bc99d61-5c49-4c65-9cf2-36c1c9415559
2736

2837
- **Streaming supported**: Enables real-time streaming of AI responses for low latency applications, with immediate validation of partial outputs. Learn more about [streaming capabilities](https://docs.workflowai.com/python-sdk/agent#streaming).
2938

39+
https://github.com/user-attachments/assets/bcb52412-4dcb-45f8-b812-4275824ed543
40+
3041
- **Provider fallback**: Automatically switches to alternative AI providers when the primary provider fails, ensuring high availability and reliability for your AI applications. This feature allows you to define fallback strategies that maintain service continuity even during provider outages or rate limiting.
3142

32-
- **Built-in tools**: Comes with powerful built-in tools like web search and web browsing capabilities, allowing your agents to access real-time information from the internet. These tools enable your AI applications to retrieve up-to-date data, research topics, and interact with web content without requiring complex integrations. Learn more about [built-in tools](https://docs.workflowai.com/python-sdk/tools).
43+
![provider-fallback](https://github.com/user-attachments/assets/cc493e94-1249-4516-b8d7-b78de7d24eb3)
44+
45+
- **Hosted tools**: Comes with powerful hosted tools like web search and web browsing capabilities, allowing your agents to access real-time information from the internet. These tools enable your AI applications to retrieve up-to-date data, research topics, and interact with web content without requiring complex integrations. Learn more about [hosted tools](https://docs.workflowai.com/python-sdk/tools#hosted-tools).
46+
47+
https://github.com/user-attachments/assets/9e1cabd1-8d1f-4cec-bad5-64871d7f033f
3348

3449
- **Custom tools support**: Easily extend your agents' capabilities by creating custom tools tailored to your specific needs. Whether you need to query internal databases, call external APIs, or perform specialized calculations, WorkflowAI's tool framework makes it simple to augment your AI with domain-specific functionality. Learn more about [custom tools](https://docs.workflowai.com/python-sdk/tools#defining-custom-tools).
3550

51+
```python
52+
# Sync tool
53+
def get_current_time(timezone: Annotated[str, "The timezone to get the current time in. e-g Europe/Paris"]) -> str:
54+
"""Return the current time in the given timezone in iso format"""
55+
return datetime.now(ZoneInfo(timezone)).isoformat()
56+
57+
# Tools can also be async
58+
async def get_latest_pip_version(package_name: Annotated[str, "The name of the pip package to check"]) -> str:
59+
"""Fetch the latest version of a pip package from PyPI"""
60+
url = f"https://pypi.org/pypi/{package_name}/json"
61+
async with httpx.AsyncClient() as client:
62+
response = await client.get(url)
63+
response.raise_for_status()
64+
data = response.json()
65+
return data['info']['version']
66+
67+
@workflowai.agent(
68+
id="research-helper",
69+
tools=[get_current_time, get_latest_pip_version],
70+
model=Model.GPT_4O_LATEST,
71+
)
72+
async def answer_question(_: AnswerQuestionInput) -> AnswerQuestionOutput:
73+
...
74+
```
75+
3676
- **Integrated with WorkflowAI**: The SDK seamlessly syncs with the WorkflowAI web application, giving you access to a powerful playground where you can edit prompts and compare models side-by-side. This hybrid approach combines the flexibility of code-first development with the visual tools needed for effective prompt engineering and model evaluation.
3777

3878
- **Multimodality support**: Build agents that can handle multiple modalities, such as images, PDFs, documents, and audio. Learn more about [multimodal capabilities](https://docs.workflowai.com/python-sdk/multimodality).
3979

40-
- **Caching support**: To save money and improve latency, WorkflowAI supports caching. When enabled, identical requests return cached results instead of making new API calls to AI providers. Learn more about [caching capabilities](https://docs.workflowai.com/python-sdk/agent#cache).
80+
https://github.com/user-attachments/assets/65d0f34e-2bb7-42bf-ab5c-be1cca96a2c6
4181

82+
- **Caching support**: To save money and improve latency, WorkflowAI supports caching. When enabled, identical requests return cached results instead of making new API calls to AI providers. Learn more about [caching capabilities](https://docs.workflowai.com/python-sdk/agent#cache).
4283

84+
- **Cost tracking**: Automatically calculates and tracks the cost of each AI model run, providing transparency and helping you manage your AI budget effectively. Learn more about [cost tracking](https://docs.workflowai.com/python-sdk/agent#cost-latency).
4385

4486
## Get Started
4587

@@ -168,14 +210,51 @@ And the runs executed via the SDK are synced with the web application.
168210

169211
Complete documentation is available at [docs.workflowai.com/python-sdk](https://docs.workflowai.com/python-sdk).
170212

171-
## Example
172-
173-
Examples are available in the [examples](./examples/) directory.
213+
## Examples
214+
215+
- [01_basic_agent.py](./examples/01_basic_agent.py): Demonstrates basic agent creation, input/output models, and cost/latency tracking.
216+
- [02_agent_with_tools.py](./examples/02_agent_with_tools.py): Shows how to use hosted tools (like `@browser-text`) and custom tools with an agent.
217+
- [03_caching.py](./examples/03_caching.py): Illustrates different caching strategies (`auto`, `always`, `never`) for agent runs.
218+
- [04_audio_classifier_agent.py](./examples/04_audio_classifier_agent.py): An agent that analyzes audio files for spam/robocall detection using audio input.
219+
- [05_browser_text_uptime_agent.py](./examples/05_browser_text_uptime_agent.py): Uses the `@browser-text` tool to fetch and extract information from web pages.
220+
- [06_streaming_summary.py](./examples/06_streaming_summary.py): Demonstrates how to stream agent responses in real-time.
221+
- [07_image_agent.py](./examples/07_image_agent.py): An agent that analyzes images to identify cities and landmarks.
222+
- [08_pdf_agent.py](./examples/08_pdf_agent.py): An agent that answers questions based on the content of a PDF document.
223+
- [09_reply.py](./examples/09_reply.py): Shows how to use the `run.reply()` method to have a conversation with an agent, maintaining context.
224+
- [10_calendar_event_extraction.py](./examples/10_calendar_event_extraction.py): Extracts structured calendar event details from text or images.
225+
- [11_ecommerce_chatbot.py](./examples/11_ecommerce_chatbot.py): A chatbot that provides product recommendations based on user queries.
226+
- [12_contextual_retrieval.py](./examples/12_contextual_retrieval.py): Generates concise contextual descriptions for document chunks to improve search retrieval.
227+
- [13_rag.py](./examples/13_rag.py): Demonstrates a RAG (Retrieval-Augmented Generation) pattern using a search tool to answer questions based on a knowledge base.
228+
- [14_templated_instructions.py](./examples/14_templated_instructions.py): Uses Jinja2 templating in agent instructions to adapt behavior based on input variables.
229+
- [15_pii_extraction.py](./examples/15_pii_extraction.py): Extracts and redacts Personal Identifiable Information (PII) from text.
230+
- [15_text_to_sql.py](./examples/15_text_to_sql.py): Converts natural language questions into safe and efficient SQL queries based on a provided database schema.
231+
- [16_multi_model_consensus.py](./examples/16_multi_model_consensus.py): Queries multiple LLMs with the same question and uses another LLM to synthesize a combined answer.
232+
- [17_multi_model_consensus_with_tools.py](./examples/17_multi_model_consensus_with_tools.py): An advanced multi-model consensus agent that uses tools to dynamically decide which models to query.
233+
- [18_flight_info_extraction.py](./examples/18_flight_info_extraction.py): Extracts structured flight information (number, dates, times, airports) from emails.
234+
- [workflows/](./examples/workflows): Contains examples of different workflow patterns (chaining, routing, parallel, orchestrator-worker). See [workflows/README.md](./examples/workflows/README.md) for details.
174235

175236
## Workflows
176237

177238
For advanced workflow patterns and examples, please refer to the [Workflows README](examples/workflows/README.md) for more details.
178239

240+
- [chain.py](./examples/workflows/chain.py): Sequential processing where tasks execute in a fixed sequence, ideal for linear processes.
241+
- [routing.py](./examples/workflows/routing.py): Directs work based on intermediate results to specialized agents, adapting behavior based on context.
242+
- [parallel_processing.py](./examples/workflows/parallel_processing.py): Splits work into independent subtasks that run concurrently for faster processing.
243+
- [orchestrator_worker.py](./examples/workflows/orchestrator_worker.py): An orchestrator plans work, and multiple worker agents execute parts in parallel.
244+
- [evaluator_optimizer.py](./examples/workflows/evaluator_optimizer.py): Employs an iterative feedback loop to evaluate and refine output quality.
245+
- [chain_of_agents.py](./examples/workflows/chain_of_agents.py): Processes long documents sequentially across multiple agents, passing findings along the chain.
246+
- [agent_delegation.py](./examples/workflows/agent_delegation.py): Enables dynamic workflows where one agent invokes other agents through tools based on the task.
247+
248+
## Cursor Integration
249+
250+
Building agents is even easier with Cursor by adding WorkflowAI docs as a documentation source:
251+
1. In Cursor chat, type `@docs`.
252+
2. Select "+ Add new doc" (at the bottom of the list).
253+
3. Add `https://docs.workflowai.com/` as a documentation source.
254+
4. Save the settings.
255+
256+
Now, Cursor will have access to the WorkflowAI docs.
257+
179258
## Contributing
180259

181260
See the [CONTRIBUTING.md](./CONTRIBUTING.md) file for more details. Thank you!

examples/01_basic_agent.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,17 @@
2020
class CityInput(BaseModel):
2121
"""Input model for the city-to-capital agent."""
2222

23-
city: str = Field(
24-
description="The name of the city for which to find the country's capital",
25-
examples=["Paris", "New York", "Tokyo"],
26-
)
23+
# For simple input fields like 'city', descriptions and examples add token overhead
24+
# without providing additional context that a modern LLM wouldn't already understand.
25+
# Input fields never need examples since an actual value will be provided at runtime.
26+
city: str = Field()
2727

2828

2929
class CapitalOutput(BaseModel):
3030
"""Output model containing information about the capital city."""
3131

32+
# Fields like country, capital, etc. are self-explanatory to LLMs
33+
# Omitting descriptions and examples for these would reduce token usage
3234
country: str = Field(
3335
description="The country where the input city is located",
3436
examples=["France", "United States", "Japan"],
@@ -45,7 +47,7 @@ class CapitalOutput(BaseModel):
4547

4648
@workflowai.agent(
4749
id="city-to-capital",
48-
model=Model.CLAUDE_3_5_SONNET_LATEST,
50+
model=Model.CLAUDE_3_7_SONNET_LATEST,
4951
)
5052
async def get_capital_info(city_input: CityInput) -> Run[CapitalOutput]:
5153
"""

examples/07_image_agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ async def main():
7474
print(f"Latency: {agent_run.duration_seconds:.2f}s")
7575

7676
# Example using URL for Image
77-
image_url = "https://t4.ftcdn.net/jpg/02/96/15/35/360_F_296153501_B34baBHDkFXbl5RmzxpiOumF4LHGCvAE.jpg"
77+
image_url = "https://workflowai.blob.core.windows.net/workflowai-public/fixtures/paris.jpg"
7878
image = Image(url=image_url)
7979
agent_run = await identify_city_from_image.run(
8080
ImageInput(image=image),

examples/15_pii_extraction.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ class PIIOutput(BaseModel):
7373

7474
@workflowai.agent(
7575
id="pii-extractor",
76-
model=Model.CLAUDE_3_5_SONNET_LATEST,
76+
model=Model.LLAMA_4_SCOUT_BASIC,
7777
)
7878
async def extract_pii(input_data: PIIInput) -> PIIOutput:
7979
"""

0 commit comments

Comments
 (0)