Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lots of new examples #297

Merged
merged 2 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions docs/examples/anonymization.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
title: Data Anonymization
description: Use ControlFlow to anonymize sensitive information in text.
icon: user-secret
---

This example demonstrates how to use ControlFlow to create a task that anonymizes sensitive information in text. It showcases the use of custom types and context passing for data privacy tasks.

## Code

The following code creates a function that takes a text string containing sensitive information and returns an anonymized version along with the replacements made:

```python
import controlflow as cf
from pydantic import BaseModel

class AnonymizationResult(BaseModel):
original: str
anonymized: str
replacements: dict[str, str]

def anonymize_text(text: str) -> AnonymizationResult:
return cf.run(
"Anonymize the given text by replacing personal information with generic placeholders",
result_type=AnonymizationResult,
context={"text": text}
)
```

Now we can use this function to anonymize text containing sensitive information:

<CodeGroup>
```python Example
original_text = "John Doe, born on 05/15/1980, lives at 123 Main St, New York. His email is [email protected]."

result = anonymize_text(original_text)
print(f"Original: {result.original}")
print(f"Anonymized: {result.anonymized}")
print("Replacements:")
for original, placeholder in result.replacements.items():
print(f" {original} -> {placeholder}")
```

```text Output
Original: John Doe, born on 05/15/1980, lives at 123 Main St, New York. His email is [email protected].
Anonymized: [NAME], born on [DATE], lives at [ADDRESS], [CITY]. His email is [EMAIL].
Replacements:
John Doe -> [NAME]
05/15/1980 -> [DATE]
123 Main St -> [ADDRESS]
New York -> [CITY]
[email protected] -> [EMAIL]
```
</CodeGroup>

## Key concepts

This implementation showcases several important ControlFlow features:

1. **[Pydantic models](/concepts/tasks/task-results#pydantic-models)**: We use a Pydantic model (`AnonymizationResult`) to define the structure of our anonymization result. This ensures that the task returns well-structured, consistent results including the original text, anonymized text, and replacements made.

```python
class AnonymizationResult(BaseModel):
original: str
anonymized: str
replacements: dict[str, str]
```

2. **[Context passing](/concepts/tasks#context)**: We pass the original text as context to the task, providing all necessary information for the anonymization process.

```python
context={"text": text}
```

By leveraging these ControlFlow features, we create an efficient and flexible data anonymization tool. This example demonstrates how ControlFlow can be used to build AI-powered privacy-enhancing workflows that can handle sensitive information with care.
99 changes: 99 additions & 0 deletions docs/examples/code-explanation.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
---
title: Code Explanation
description: Use ControlFlow to generate natural language explanations of code snippets.
icon: code
---

This example demonstrates how to use ControlFlow to create a task that explains code snippets in natural language. It showcases the use of custom types and context passing for code documentation tasks.

## Code

The following code creates a function that takes a code snippet and its programming language, then returns an explanation of the code:

```python
import controlflow as cf
from pydantic import BaseModel

class CodeExplanation(BaseModel):
code: str
explanation: str
language: str

def explain_code(code: str, language: str=None) -> CodeExplanation:
return cf.run(
f"Explain the following code snippet",
result_type=CodeExplanation,
context={"code": code, "language": language or 'auto-detect'}
)
```

Now we can use this function to explain a code snippet:

<CodeGroup>
```python Example
code_snippet = """
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
"""

result = explain_code(code_snippet, "Python")
print(f"Code:\n{result.code}\n")
print(f"Explanation:\n{result.explanation}")
```

```text Output
Code:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

Explanation:
This Python code defines a function called `fibonacci` that calculates
the nth number in the Fibonacci sequence using recursion. Here's a
breakdown of how it works:

1. The function takes a single parameter `n`, which represents the
position in the Fibonacci sequence we want to calculate.

2. There's a base case: if `n` is less than or equal to 1, the function
simply returns `n`. This handles the first two numbers in the Fibonacci
sequence (F(0) = 0 and F(1) = 1).

3. For any other value of `n`, the function recursively calls itself twice:
- Once with `n-1` as the argument
- Once with `n-2` as the argument

4. The results of these two recursive calls are added together and returned.

This implementation follows the mathematical definition of the Fibonacci
sequence, where each number is the sum of the two preceding ones. However,
it's worth noting that this recursive approach can be inefficient for
large values of `n` due to repeated calculations.
```
</CodeGroup>

## Key concepts

This implementation showcases several important ControlFlow features:

1. **[Pydantic models](/concepts/tasks/task-results#pydantic-models)**: We use a Pydantic model (`CodeExplanation`) to define the structure of our explanation result. This ensures that the task returns well-structured, consistent results including the original code, its explanation, and the programming language.

```python
class CodeExplanation(BaseModel):
code: str
explanation: str
language: str
```

2. **[Context passing](/concepts/tasks#context)**: We pass both the code snippet and the programming language as context to the task, providing all necessary information for the explanation process.

```python
context={"code": code, "language": language}
```

By leveraging these ControlFlow features, we create an efficient and flexible code explanation tool. This example demonstrates how ControlFlow can be used to build AI-powered documentation workflows that can help developers understand and explain code snippets in natural language.
122 changes: 122 additions & 0 deletions docs/examples/examples-guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Guide for Creating ControlFlow Examples

This guide outlines the process for creating clear, informative, and consistent examples for ControlFlow documentation. Follow these steps to produce high-quality examples that showcase ControlFlow's features and capabilities.

## 1. Example Structure

Each example should follow this general structure:

```markdown
---
title: [Concise Title]
description: [Brief description of what the example demonstrates]
icon: [FontAwesome icon name]
---

[1-2 sentence introduction explaining the task and its relevance]

## Code

[Brief explanation of what the code does]

```python
[Code block demonstrating the ControlFlow implementation]
```

[Usage examples in a CodeGroup, if applicable, as it creates a single tabbed view]

<CodeGroup>
```python Code
[Full, copyable code for the example, including prints]
```
```text Result
the result, including any intermiediate output that might be helpful
```
</CodeGroup>


ALTERNATIVELY, use a code block for a single example including a commented result

ALTERNATIVELY, use a CodeGroup for multiple examples with commented results



## Key concepts

[Explanation of key ControlFlow features demonstrated in the example]

1. **[Feature Name](/link-to-docs)**: [Brief explanation of the feature]

```python
[Code snippet illustrating the feature]
```

[2-3 sentences wrapping up the example and its significance]
```

## 2. Title and Description

- Use a concise, descriptive title that clearly indicates the task or concept being demonstrated.
- Provide a brief (1-2 sentence) description that expands on the title and gives context.
- Choose an appropriate FontAwesome icon that represents the task or concept.

## 3. Introduction

- Begin with a 1-2 sentence introduction that explains the task or concept and its relevance in natural language processing or AI applications.
- If the example demonstrates multiple approaches or variations, briefly mention this.

## 4. Code Section

- Start with a brief explanation of what the code does and how it approaches the task.
- Present the main implementation code in a clear, well-commented Python code block.
- If there are multiple variations or approaches, present them sequentially, explaining the differences between each approach.
- Use type hints and follow PEP 8 style guidelines in the code.
- Import `controlflow as cf` at the beginning of each code block so it can be copied directly.
- Do not create agents unless you are demonstrating a specific feature (e.g. LLM selection, instructions, reusable tools, etc.)
- Try to write code that is as short as possible while still being clear and demonstrating the feature.
- Only use a flow if your tasks need to share history, otherwise just use a single task
- Do not import Dict or List from typing; use builtin dict or list instead

## 5. Usage Examples

- Provide 1-3 usage examples that demonstrate how to use the implemented function(s).
- Use the `<CodeGroup>` component to organize multiple examples.
- Include both the input and the expected output in the examples.
- Choose diverse and relevant examples that showcase different aspects of the implementation.

## 6. Key Concepts

- Identify 3-5 key ControlFlow features or concepts demonstrated in the example (if possible)
- For each concept:
1. Provide a brief explanation of what the feature does and why it's important.
2. Include a code snippet that illustrates the feature in use.
3. Link to the relevant ControlFlow documentation for that feature.
- Arrange the concepts in order of importance or complexity.
- Do not consider controlflow basics like creating or running a task to be key concepts (or even "simple task creation")

## 7. Conclusion

- End with 2-3 sentences that wrap up the example, emphasizing its significance and how it showcases ControlFlow's capabilities.
- Mention any potential extensions or variations of the example that users might consider.

## 8. Style and Tone

- Use clear, concise language throughout the example.
- Maintain a professional and educational tone, avoiding overly casual language.
- Assume the reader has basic programming knowledge but may be new to ControlFlow.
- Use active voice and present tense where possible.

## 9. Consistency

- Ensure consistency in formatting, terminology, and style across all examples.
- Use the same naming conventions for variables and functions across related examples.
- Maintain a consistent level of detail and explanation across examples.

## 10. Review and Refinement

- After creating the example, review it for clarity, correctness, and completeness.
- Ensure all code is functional and produces the expected results.
- Check that all links to ControlFlow documentation are correct and up-to-date.
- Refine the language and explanations to be as clear and concise as possible.

By following this guide, you'll create informative, consistent, and high-quality examples that effectively showcase ControlFlow's features and capabilities. These examples will help users understand how to implement various NLP and AI tasks using ControlFlow, encouraging adoption and proper usage of the framework.
Loading