From 99c44492721a4f11202edad318e298707268ca05 Mon Sep 17 00:00:00 2001 From: Suresh Veeragoni Date: Fri, 11 Jul 2025 19:02:02 -0700 Subject: [PATCH 1/3] models - DeepSeek documentation support --- .../python/deepseek_code_completion.md | 323 +++++++++++++++++ .../python/deepseek_code_completion.py | 294 ++++++++++++++++ .../python/deepseek_reasoning_agent.md | 325 ++++++++++++++++++ .../python/deepseek_reasoning_agent.py | 247 +++++++++++++ .../concepts/model-providers/deepseek.md | 164 +++++++++ docs/user-guide/quickstart.md | 1 + mkdocs.yml | 3 + 7 files changed, 1357 insertions(+) create mode 100644 docs/examples/python/deepseek_code_completion.md create mode 100644 docs/examples/python/deepseek_code_completion.py create mode 100644 docs/examples/python/deepseek_reasoning_agent.md create mode 100644 docs/examples/python/deepseek_reasoning_agent.py create mode 100644 docs/user-guide/concepts/model-providers/deepseek.md diff --git a/docs/examples/python/deepseek_code_completion.md b/docs/examples/python/deepseek_code_completion.md new file mode 100644 index 00000000..320053bb --- /dev/null +++ b/docs/examples/python/deepseek_code_completion.md @@ -0,0 +1,323 @@ +# DeepSeek Code Completion Example + +This example demonstrates how to use DeepSeek models for Fill-in-the-Middle (FIM) code completion tasks with Strands Agents. DeepSeek models excel at understanding code context and generating high-quality completions for functions, classes, and algorithms. + +## What You'll Learn + +- How to use DeepSeek for code completion tasks +- Best practices for FIM (Fill-in-the-Middle) prompting +- Configuring DeepSeek models for consistent code generation +- Various code completion scenarios from simple functions to complex algorithms + +## Prerequisites + +Before running this example, you'll need: + +1. A DeepSeek API key from [DeepSeek Platform](https://platform.deepseek.com/) +2. Set the environment variable: `export DEEPSEEK_API_KEY="your-api-key"` +3. Install DeepSeek dependencies: `pip install 'strands-agents[deepseek]'` + +## Key Features Demonstrated + +### 1. Function Completion + +Complete missing function implementations with proper logic: + +```python +model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 500, + "temperature": 0.2, # Lower temperature for consistent code + } +) + +prompt = """ +Complete this Python function: + +```python +def calculate_compound_interest(principal, rate, time, compound_frequency): + '''Calculate compound interest.''' + # TODO: Implement the compound interest formula + pass +``` +""" +``` + +### 2. Class Method Implementation + +Fill in missing methods in object-oriented code: + +```python +prompt = """ +Complete the missing methods in this Python class: + +```python +class BankAccount: + def __init__(self, account_number, initial_balance=0): + self.account_number = account_number + self.balance = initial_balance + + def deposit(self, amount): + # TODO: Implement deposit method + pass + + def withdraw(self, amount): + # TODO: Implement withdraw method with overdraft protection + pass +``` +""" +``` + +### 3. Algorithm Implementation + +Complete complex data structures and algorithms: + +```python +prompt = """ +Complete this binary search tree implementation: + +```python +class BinarySearchTree: + def __init__(self): + self.root = None + + def insert(self, val): + # TODO: Insert a value into the BST + pass + + def search(self, val): + # TODO: Search for a value in the BST + pass +``` +""" +``` + +### 4. Code Refactoring + +Improve existing code for better performance and readability: + +```python +prompt = """ +Refactor this code to make it more efficient and readable: + +```python +def process_data(data): + result = [] + for i in range(len(data)): + if data[i] > 0: + # ... inefficient code +``` + +Improve by making it more Pythonic and performant. +""" +``` + +### 5. API Integration + +Complete REST API client implementations: + +```python +prompt = """ +Complete this REST API client class: + +```python +class WeatherAPIClient: + def __init__(self, api_key: str): + self.api_key = api_key + + def get_current_weather(self, city: str) -> Dict: + # TODO: Implement method to get current weather + pass +``` +""" +``` + +## Complete Example Code + +```python +#!/usr/bin/env python3 +""" +DeepSeek Code Completion Example + +This example demonstrates how to use DeepSeek models for Fill-in-the-Middle (FIM) +code completion tasks with Strands Agents. +""" + +import os +from strands import Agent +from strands.models.deepseek import DeepSeekModel + + +def basic_function_completion(): + """Complete a basic function implementation.""" + print("\\n--- Basic Function Completion ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 500, + "temperature": 0.2, # Lower temperature for consistent code + } + ) + + agent = Agent(model=model) + + prompt = \"\"\" + Complete this Python function: + + ```python + def calculate_compound_interest(principal, rate, time, compound_frequency): + ''' + Calculate compound interest. + + Args: + principal: Initial amount + rate: Annual interest rate (as decimal, e.g., 0.05 for 5%) + time: Time in years + compound_frequency: Number of times interest compounds per year + + Returns: + Final amount after compound interest + ''' + # TODO: Implement the compound interest formula + pass + ``` + + Provide the complete implementation. + \"\"\" + + response = agent(prompt) + print("Completed function:") + print(response.message["content"][0]["text"]) + + +def algorithm_completion(): + """Complete a complex algorithm implementation.""" + print("\\n--- Algorithm Completion ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1000, + "temperature": 0.15, + } + ) + + agent = Agent(model=model) + + prompt = \"\"\" + Complete this binary search tree implementation: + + ```python + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + class BinarySearchTree: + def __init__(self): + self.root = None + + def insert(self, val): + # TODO: Insert a value into the BST + pass + + def search(self, val): + # TODO: Search for a value in the BST + pass + + def inorder_traversal(self): + # TODO: Return inorder traversal as a list + pass + ``` + + Implement all methods with proper BST logic. + \"\"\" + + response = agent(prompt) + print("Completed BST implementation:") + print(response.message["content"][0]["text"]) + + +if __name__ == "__main__": + print("DeepSeek Code Completion Examples\\n") + + # Check if API key is available + if not os.getenv("DEEPSEEK_API_KEY"): + print("Please set DEEPSEEK_API_KEY environment variable to run these examples.") + exit(1) + + try: + basic_function_completion() + algorithm_completion() + + except Exception as e: + print(f"Error running examples: {e}") + print("Make sure you have a valid DeepSeek API key and sufficient credits.") + + print("\\nCode completion examples completed.") +``` + +## Running the Example + +1. Set your DeepSeek API key: + ```bash + export DEEPSEEK_API_KEY="your-deepseek-api-key" + ``` + +2. Install dependencies: + ```bash + pip install 'strands-agents[deepseek]' + ``` + +3. Run the example: + ```bash + python deepseek_code_completion.py + ``` + +## Best Practices for Code Completion + +### Temperature Settings +- **Low temperature (0.1-0.2)**: For consistent, predictable code completion +- **Medium temperature (0.3-0.5)**: For creative solutions while maintaining correctness +- **Higher temperature (0.6+)**: Generally not recommended for code completion + +### Prompt Structure +1. **Clear Context**: Provide sufficient context about what the code should do +2. **Specific TODOs**: Use clear TODO comments to indicate what needs completion +3. **Type Hints**: Include type hints when possible for better completions +4. **Documentation**: Include docstrings to guide the completion + +### Token Limits +- **Simple functions**: 300-500 tokens usually sufficient +- **Complex algorithms**: 800-1200 tokens for comprehensive implementations +- **Large classes**: May need 1500+ tokens for complete implementations + +## Use Cases + +This example demonstrates several practical use cases: + +- **Development Assistance**: Complete partially written functions and classes +- **Learning Tool**: Generate implementations to understand algorithms +- **Code Review**: Get alternative implementations for comparison +- **Rapid Prototyping**: Quickly scaffold code structures +- **Legacy Code**: Complete or modernize existing codebases + +## Key Takeaways + +- DeepSeek models excel at understanding code context and generating syntactically correct completions +- Lower temperature settings produce more consistent and reliable code +- Clear, specific prompts with good context lead to better completions +- The models can handle various programming paradigms from functional to object-oriented code +- Proper error handling and edge cases are often included in generated completions + +## Learn More + +- [DeepSeek Model Provider Documentation](../../user-guide/concepts/model-providers/deepseek.md) +- [DeepSeek Reasoning Agent Example](deepseek_reasoning_agent.md) +- [DeepSeek Platform](https://platform.deepseek.com/) \ No newline at end of file diff --git a/docs/examples/python/deepseek_code_completion.py b/docs/examples/python/deepseek_code_completion.py new file mode 100644 index 00000000..1404a722 --- /dev/null +++ b/docs/examples/python/deepseek_code_completion.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +""" +DeepSeek Code Completion Example + +This example demonstrates how to use DeepSeek models for Fill-in-the-Middle (FIM) +code completion tasks with Strands Agents. +""" + +import os +from strands import Agent +from strands.models.deepseek import DeepSeekModel + + +def basic_function_completion(): + """Complete a basic function implementation.""" + print("\n--- Basic Function Completion ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 500, + "temperature": 0.2, # Lower temperature for consistent code + } + ) + + agent = Agent(model=model) + + prompt = """ + Complete this Python function: + + ```python + def calculate_compound_interest(principal, rate, time, compound_frequency): + ''' + Calculate compound interest. + + Args: + principal: Initial amount + rate: Annual interest rate (as decimal, e.g., 0.05 for 5%) + time: Time in years + compound_frequency: Number of times interest compounds per year + + Returns: + Final amount after compound interest + ''' + # TODO: Implement the compound interest formula + pass + ``` + + Provide the complete implementation. + """ + + response = agent(prompt) + print("Completed function:") + print(response.message["content"][0]["text"]) + + +def class_method_completion(): + """Complete missing methods in a class.""" + print("\n--- Class Method Completion ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 800, + "temperature": 0.1, + } + ) + + agent = Agent(model=model) + + prompt = """ + Complete the missing methods in this Python class: + + ```python + class BankAccount: + def __init__(self, account_number, initial_balance=0): + self.account_number = account_number + self.balance = initial_balance + self.transaction_history = [] + + def deposit(self, amount): + # TODO: Implement deposit method + pass + + def withdraw(self, amount): + # TODO: Implement withdraw method with overdraft protection + pass + + def get_balance(self): + # TODO: Return current balance + pass + + def get_transaction_history(self): + # TODO: Return transaction history + pass + ``` + + Implement all the missing methods with proper error handling. + """ + + response = agent(prompt) + print("Completed class:") + print(response.message["content"][0]["text"]) + + +def algorithm_completion(): + """Complete a complex algorithm implementation.""" + print("\n--- Algorithm Completion ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1000, + "temperature": 0.15, + } + ) + + agent = Agent(model=model) + + prompt = """ + Complete this binary search tree implementation: + + ```python + class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + class BinarySearchTree: + def __init__(self): + self.root = None + + def insert(self, val): + # TODO: Insert a value into the BST + pass + + def search(self, val): + # TODO: Search for a value in the BST + pass + + def inorder_traversal(self): + # TODO: Return inorder traversal as a list + pass + + def _insert_recursive(self, node, val): + # TODO: Helper method for recursive insertion + pass + + def _search_recursive(self, node, val): + # TODO: Helper method for recursive search + pass + + def _inorder_recursive(self, node, result): + # TODO: Helper method for recursive inorder traversal + pass + ``` + + Implement all methods with proper BST logic. + """ + + response = agent(prompt) + print("Completed BST implementation:") + print(response.message["content"][0]["text"]) + + +def code_refactoring_example(): + """Use DeepSeek to refactor and improve existing code.""" + print("\n--- Code Refactoring Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1200, + "temperature": 0.3, + } + ) + + agent = Agent(model=model) + + prompt = """ + Refactor this code to make it more efficient and readable: + + ```python + def process_data(data): + result = [] + for i in range(len(data)): + if data[i] > 0: + temp = data[i] * 2 + if temp < 100: + result.append(temp) + else: + result.append(100) + else: + result.append(0) + + final_result = [] + for item in result: + if item not in final_result: + final_result.append(item) + + return final_result + ``` + + Improve this code by: + 1. Making it more Pythonic + 2. Improving performance + 3. Adding proper documentation + 4. Using appropriate data structures + """ + + response = agent(prompt) + print("Refactored code:") + print(response.message["content"][0]["text"]) + + +def api_integration_completion(): + """Complete an API integration example.""" + print("\n--- API Integration Completion ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 800, + "temperature": 0.2, + } + ) + + agent = Agent(model=model) + + prompt = """ + Complete this REST API client class: + + ```python + import requests + import json + from typing import Dict, List, Optional + + class WeatherAPIClient: + def __init__(self, api_key: str, base_url: str = "https://api.weather.com"): + self.api_key = api_key + self.base_url = base_url + self.session = requests.Session() + + def get_current_weather(self, city: str) -> Dict: + # TODO: Implement method to get current weather for a city + pass + + def get_forecast(self, city: str, days: int = 5) -> List[Dict]: + # TODO: Implement method to get weather forecast + pass + + def _make_request(self, endpoint: str, params: Dict) -> Dict: + # TODO: Helper method to make API requests with error handling + pass + + def _handle_api_error(self, response: requests.Response): + # TODO: Handle different types of API errors + pass + ``` + + Implement all methods with proper error handling and documentation. + """ + + response = agent(prompt) + print("Completed API client:") + print(response.message["content"][0]["text"]) + + +if __name__ == "__main__": + print("DeepSeek Code Completion Examples\n") + + # Check if API key is available + if not os.getenv("DEEPSEEK_API_KEY"): + print("Please set DEEPSEEK_API_KEY environment variable to run these examples.") + exit(1) + + try: + basic_function_completion() + class_method_completion() + algorithm_completion() + code_refactoring_example() + api_integration_completion() + + except Exception as e: + print(f"Error running examples: {e}") + print("Make sure you have a valid DeepSeek API key and sufficient credits.") + + print("\nCode completion examples completed.") \ No newline at end of file diff --git a/docs/examples/python/deepseek_reasoning_agent.md b/docs/examples/python/deepseek_reasoning_agent.md new file mode 100644 index 00000000..4fe878bf --- /dev/null +++ b/docs/examples/python/deepseek_reasoning_agent.md @@ -0,0 +1,325 @@ +# DeepSeek Reasoning Agent Example + +This example demonstrates how to use DeepSeek models with Strands Agents, showcasing both the chat and reasoning models for different use cases including complex problem-solving, code completion (Fill-in-the-Middle), and structured output. + +## What You'll Learn + +- How to use DeepSeek's chat and reasoning models +- Leveraging reasoning models for complex problem-solving +- Using DeepSeek for code completion and analysis +- Combining structured output with reasoning capabilities +- Best practices for different DeepSeek model configurations + +## Prerequisites + +Before running this example, you'll need: + +1. A DeepSeek API key from [DeepSeek Platform](https://platform.deepseek.com/) +2. Set the environment variable: `export DEEPSEEK_API_KEY="your-api-key"` +3. Install DeepSeek dependencies: `pip install 'strands-agents[deepseek]'` + +## Key Features Demonstrated + +### 1. Basic Chat Model Usage + +The example shows how to use DeepSeek's general-purpose chat model for everyday conversations and explanations: + +```python +model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1000, + "temperature": 0.7, + } +) + +agent = Agent(model=model) +response = agent("Explain quantum computing in simple terms.") +``` + +### 2. Reasoning Model for Complex Problems + +DeepSeek's reasoning model excels at step-by-step problem-solving: + +```python +reasoning_model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-reasoner", + params={ + "max_tokens": 32000, # Reasoning models need more tokens + } +) + +# Complex multi-step problem +problem = """ +A company has 3 departments: Sales, Marketing, and Engineering. +- Sales has 25% more employees than Marketing +- Engineering has 40% fewer employees than Sales +- The total number of employees across all departments is 180 + +How many employees are in each department? +""" + +response = agent(problem) +``` + +### 3. Code Completion (Fill-in-the-Middle) + +DeepSeek models are excellent for code completion tasks: + +```python +fim_prompt = """ +Complete the missing function implementation: + +```python +def fibonacci_sequence(n): + '''Generate the first n numbers in the Fibonacci sequence.''' + # TODO: Implement this function + pass +``` + +Fill in the implementation for the fibonacci_sequence function. +""" + +response = agent(fim_prompt) +``` + +### 4. Structured Reasoning Output + +Combine the power of reasoning models with structured output: + +```python +class MathProblem(BaseModel): + """Structured representation of a math problem solution.""" + problem_type: str = Field(description="Type of mathematical problem") + given_information: List[str] = Field(description="List of given facts") + solution_steps: List[str] = Field(description="Step-by-step solution process") + final_answer: str = Field(description="Final numerical answer with units") + verification: Optional[str] = Field(description="Verification of the answer") + +result = agent.structured_output(MathProblem, complex_problem) +``` + +### 5. Code Analysis + +Use DeepSeek for comprehensive code analysis: + +```python +class CodeAnalysis(BaseModel): + language: str = Field(description="Programming language") + complexity: str = Field(description="Time/space complexity analysis") + improvements: List[str] = Field(description="Suggested improvements") + bugs: List[str] = Field(description="Potential bugs or issues") + explanation: str = Field(description="What the code does") + +result = agent.structured_output(CodeAnalysis, code_to_analyze) +``` + +## Complete Example Code + +```python +#!/usr/bin/env python3 +""" +DeepSeek Reasoning Agent Example + +This example demonstrates how to use DeepSeek models with Strands Agents, +showcasing both the chat and reasoning models for different use cases. +""" + +import os +from typing import List, Optional +from pydantic import BaseModel, Field +from strands import Agent +from strands.models.deepseek import DeepSeekModel + + +def basic_chat_example(): + """Basic example using DeepSeek chat model.""" + print("\\n--- Basic Chat Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1000, + "temperature": 0.7, + } + ) + + agent = Agent(model=model) + response = agent("Explain quantum computing in simple terms.") + + print("Response:", response.message["content"][0]["text"]) + + +def reasoning_model_example(): + """Example using DeepSeek reasoning model for complex problem solving.""" + print("\\n--- Reasoning Model Example ---") + + reasoning_model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-reasoner", + params={ + "max_tokens": 32000, # Reasoning models need more tokens + } + ) + + agent = Agent(model=reasoning_model) + + # Complex math problem that benefits from step-by-step reasoning + problem = \"\"\" + A company has 3 departments: Sales, Marketing, and Engineering. + - Sales has 25% more employees than Marketing + - Engineering has 40% fewer employees than Sales + - The total number of employees across all departments is 180 + + How many employees are in each department? + \"\"\" + + response = agent(problem) + print("Reasoning and Solution:") + print(response.message["content"][0]["text"]) + + +def code_completion_example(): + """Example using DeepSeek for Fill-in-the-Middle (FIM) code completion.""" + print("\\n--- Code Completion (FIM) Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 500, + "temperature": 0.2, # Lower temperature for more consistent code + } + ) + + agent = Agent(model=model) + + # FIM-style prompt for code completion + fim_prompt = \"\"\" + Complete the missing function implementation: + + ```python + def fibonacci_sequence(n): + '''Generate the first n numbers in the Fibonacci sequence.''' + # TODO: Implement this function + # Should return a list of the first n Fibonacci numbers + pass + + def main(): + result = fibonacci_sequence(10) + print(f"First 10 Fibonacci numbers: {result}") + ``` + + Fill in the implementation for the fibonacci_sequence function. + \"\"\" + + response = agent(fim_prompt) + print("Code completion:") + print(response.message["content"][0]["text"]) + + +class MathProblem(BaseModel): + """Structured representation of a math problem solution.""" + problem_type: str = Field(description="Type of mathematical problem") + given_information: List[str] = Field(description="List of given facts") + solution_steps: List[str] = Field(description="Step-by-step solution process") + final_answer: str = Field(description="Final numerical answer with units") + verification: Optional[str] = Field(description="Verification of the answer") + + +def structured_reasoning_example(): + """Example combining structured output with reasoning model.""" + print("\\n--- Structured Reasoning Example ---") + + reasoning_model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-reasoner", + params={ + "max_tokens": 32000, + } + ) + + agent = Agent(model=reasoning_model) + + problem = \"\"\" + A water tank can be filled by two pipes. Pipe A can fill the tank in 6 hours, + and Pipe B can fill it in 4 hours. If both pipes work together, how long will + it take to fill the tank? + \"\"\" + + result = agent.structured_output(MathProblem, problem) + + print(f"Problem Type: {result.problem_type}") + print(f"Given Information: {result.given_information}") + print("\\nSolution Steps:") + for i, step in enumerate(result.solution_steps, 1): + print(f" {i}. {step}") + print(f"\\nFinal Answer: {result.final_answer}") + if result.verification: + print(f"Verification: {result.verification}") + + +if __name__ == "__main__": + print("DeepSeek Reasoning Agent Examples\\n") + + # Check if API key is available + if not os.getenv("DEEPSEEK_API_KEY"): + print("Please set DEEPSEEK_API_KEY environment variable to run these examples.") + exit(1) + + try: + basic_chat_example() + reasoning_model_example() + code_completion_example() + structured_reasoning_example() + + except Exception as e: + print(f"Error running examples: {e}") + print("Make sure you have a valid DeepSeek API key and sufficient credits.") + + print("\\nExamples completed.") +``` + +## Running the Example + +1. Set your DeepSeek API key: + ```bash + export DEEPSEEK_API_KEY="your-deepseek-api-key" + ``` + +2. Install dependencies: + ```bash + pip install 'strands-agents[deepseek]' + ``` + +3. Run the example: + ```bash + python deepseek_reasoning_agent.py + ``` + +## Key Takeaways + +- **DeepSeek Chat Model**: Great for general conversations, explanations, and code completion +- **DeepSeek Reasoning Model**: Excels at complex problem-solving with step-by-step reasoning +- **Structured Output**: Works well with both models for type-safe responses +- **Code Tasks**: DeepSeek models are particularly strong at programming-related tasks +- **Token Limits**: Reasoning models typically need higher token limits (32k recommended) +- **Temperature Settings**: Use lower temperatures (0.2-0.3) for code tasks, higher (0.7-0.8) for creative tasks + +## Use Cases + +This example demonstrates several practical use cases: + +- **Educational**: Step-by-step problem solving for math and science +- **Development**: Code completion, analysis, and debugging assistance +- **Business**: Complex calculations and data analysis +- **Research**: Structured information extraction and reasoning + +## Learn More + +- [DeepSeek Model Provider Documentation](../../user-guide/concepts/model-providers/deepseek.md) +- [Structured Output Guide](../../user-guide/concepts/agents/structured-output.md) +- [DeepSeek Platform](https://platform.deepseek.com/) \ No newline at end of file diff --git a/docs/examples/python/deepseek_reasoning_agent.py b/docs/examples/python/deepseek_reasoning_agent.py new file mode 100644 index 00000000..9ab9084c --- /dev/null +++ b/docs/examples/python/deepseek_reasoning_agent.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +""" +DeepSeek Reasoning Agent Example + +This example demonstrates how to use DeepSeek models with Strands Agents, +showcasing both the chat and reasoning models for different use cases. +""" + +import os +from typing import List, Optional +from pydantic import BaseModel, Field +from strands import Agent +from strands.models.deepseek import DeepSeekModel + + +def basic_chat_example(): + """Basic example using DeepSeek chat model.""" + print("\n--- Basic Chat Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1000, + "temperature": 0.7, + } + ) + + agent = Agent(model=model) + response = agent("Explain quantum computing in simple terms.") + + print("Response:", response.message["content"][0]["text"]) + + +def reasoning_model_example(): + """Example using DeepSeek reasoning model for complex problem solving.""" + print("\n--- Reasoning Model Example ---") + + reasoning_model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-reasoner", + params={ + "max_tokens": 32000, # Reasoning models need more tokens + } + ) + + agent = Agent(model=reasoning_model) + + # Complex math problem that benefits from step-by-step reasoning + problem = """ + A company has 3 departments: Sales, Marketing, and Engineering. + - Sales has 25% more employees than Marketing + - Engineering has 40% fewer employees than Sales + - The total number of employees across all departments is 180 + + How many employees are in each department? + """ + + response = agent(problem) + print("Reasoning and Solution:") + print(response.message["content"][0]["text"]) + + +def code_completion_example(): + """Example using DeepSeek for Fill-in-the-Middle (FIM) code completion.""" + print("\n--- Code Completion (FIM) Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 500, + "temperature": 0.2, # Lower temperature for more consistent code + } + ) + + agent = Agent(model=model) + + # FIM-style prompt for code completion + fim_prompt = """ + Complete the missing function implementation: + + ```python + def fibonacci_sequence(n): + '''Generate the first n numbers in the Fibonacci sequence.''' + # TODO: Implement this function + # Should return a list of the first n Fibonacci numbers + pass + + def main(): + result = fibonacci_sequence(10) + print(f"First 10 Fibonacci numbers: {result}") + ``` + + Fill in the implementation for the fibonacci_sequence function. + """ + + response = agent(fim_prompt) + print("Code completion:") + print(response.message["content"][0]["text"]) + + +class MathProblem(BaseModel): + """Structured representation of a math problem solution.""" + problem_type: str = Field(description="Type of mathematical problem") + given_information: List[str] = Field(description="List of given facts") + solution_steps: List[str] = Field(description="Step-by-step solution process") + final_answer: str = Field(description="Final numerical answer with units") + verification: Optional[str] = Field(description="Verification of the answer") + + +def structured_reasoning_example(): + """Example combining structured output with reasoning model.""" + print("\n--- Structured Reasoning Example ---") + + reasoning_model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-reasoner", + params={ + "max_tokens": 32000, + } + ) + + agent = Agent(model=reasoning_model) + + problem = """ + A water tank can be filled by two pipes. Pipe A can fill the tank in 6 hours, + and Pipe B can fill it in 4 hours. If both pipes work together, how long will + it take to fill the tank? + """ + + result = agent.structured_output(MathProblem, problem) + + print(f"Problem Type: {result.problem_type}") + print(f"Given Information: {result.given_information}") + print("\nSolution Steps:") + for i, step in enumerate(result.solution_steps, 1): + print(f" {i}. {step}") + print(f"\nFinal Answer: {result.final_answer}") + if result.verification: + print(f"Verification: {result.verification}") + + +class CodeAnalysis(BaseModel): + """Structured analysis of code.""" + language: str = Field(description="Programming language") + complexity: str = Field(description="Time/space complexity analysis") + improvements: List[str] = Field(description="Suggested improvements") + bugs: List[str] = Field(description="Potential bugs or issues") + explanation: str = Field(description="What the code does") + + +def code_analysis_example(): + """Example using DeepSeek for structured code analysis.""" + print("\n--- Code Analysis Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 2000, + "temperature": 0.3, + } + ) + + agent = Agent(model=model) + + code_to_analyze = ''' + def bubble_sort(arr): + n = len(arr) + for i in range(n): + for j in range(0, n-i-1): + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] + return arr + + numbers = [64, 34, 25, 12, 22, 11, 90] + sorted_numbers = bubble_sort(numbers) + print(sorted_numbers) + ''' + + prompt = f"Analyze this code:\n\n{code_to_analyze}" + + result = agent.structured_output(CodeAnalysis, prompt) + + print(f"Language: {result.language}") + print(f"Explanation: {result.explanation}") + print(f"Complexity: {result.complexity}") + print("\nSuggested Improvements:") + for improvement in result.improvements: + print(f" • {improvement}") + print("\nPotential Issues:") + for bug in result.bugs: + print(f" • {bug}") + + +async def streaming_example(): + """Example of streaming responses from DeepSeek.""" + print("\n--- Streaming Example ---") + + model = DeepSeekModel( + api_key=os.getenv("DEEPSEEK_API_KEY"), + model_id="deepseek-chat", + params={ + "max_tokens": 1000, + "temperature": 0.8, + } + ) + + agent = Agent(model=model) + + print("Streaming response for creative writing:") + print("Prompt: Write a short story about a robot learning to paint") + print("\nResponse:") + + async for event in agent.stream_async("Write a short story about a robot learning to paint"): + if "result" in event: + # Final result + break + # Print streaming content as it arrives + # Note: Actual streaming implementation may vary + + +if __name__ == "__main__": + print("DeepSeek Reasoning Agent Examples\n") + + # Check if API key is available + if not os.getenv("DEEPSEEK_API_KEY"): + print("Please set DEEPSEEK_API_KEY environment variable to run these examples.") + exit(1) + + try: + basic_chat_example() + reasoning_model_example() + code_completion_example() + structured_reasoning_example() + code_analysis_example() + + # Note: Async example would need to be run in an async context + # import asyncio + # asyncio.run(streaming_example()) + + except Exception as e: + print(f"Error running examples: {e}") + print("Make sure you have a valid DeepSeek API key and sufficient credits.") + + print("\nExamples completed.") \ No newline at end of file diff --git a/docs/user-guide/concepts/model-providers/deepseek.md b/docs/user-guide/concepts/model-providers/deepseek.md new file mode 100644 index 00000000..618e89d2 --- /dev/null +++ b/docs/user-guide/concepts/model-providers/deepseek.md @@ -0,0 +1,164 @@ +# DeepSeek + +[DeepSeek](https://platform.deepseek.com/) is an AI company that provides powerful language models including reasoning-capable models. The Strands Agents SDK implements a DeepSeek provider, allowing you to run agents against DeepSeek's chat and reasoning models. + +## Installation + +DeepSeek is configured as an optional dependency in Strands Agents. To install, run: + +```bash +pip install 'strands-agents[deepseek]' +``` + +## Usage + +After installing the DeepSeek dependencies, you can import and initialize the Strands Agents' DeepSeek provider as follows: + +```python +from strands import Agent +from strands.models.deepseek import DeepSeekModel +from strands_tools import calculator + +model = DeepSeekModel( + api_key="", + model_id="deepseek-chat", + params={ + "max_tokens": 2000, + "temperature": 0.7, + } +) + +agent = Agent(model=model, tools=[calculator]) +response = agent("What is 2+2") +print(response) +``` + +### Using the Reasoning Model + +DeepSeek's reasoning model provides enhanced problem-solving capabilities: + +```python +reasoning_model = DeepSeekModel( + api_key="", + model_id="deepseek-reasoner", + params={ + "max_tokens": 32000, # Reasoning models typically need more tokens + } +) + +agent = Agent(model=reasoning_model) +response = agent("Solve this step by step: If a train travels 120 km in 2 hours, and then 180 km in the next 3 hours, what is its average speed for the entire journey?") +print(response) +``` + +### Using Beta Endpoint + +To access beta features, enable the beta endpoint: + +```python +beta_model = DeepSeekModel( + api_key="", + model_id="deepseek-chat", + use_beta=True, + params={ + "max_tokens": 1000, + } +) +``` + +## Configuration + +### Model Configuration + +The `DeepSeekModel` supports the following configuration options: + +| Parameter | Description | Example | Options | +|-----------|-------------|---------|---------| +| `api_key` | DeepSeek API key | `"sk-..."` | Required | +| `model_id` | ID of the model to use | `"deepseek-chat"` | `"deepseek-chat"`, `"deepseek-reasoner"` | +| `base_url` | Custom API base URL | `"https://api.deepseek.com"` | Optional | +| `use_beta` | Whether to use beta endpoint | `True` | `True`, `False` (default) | +| `params` | Model-specific parameters | `{"max_tokens": 2000, "temperature": 0.7}` | [API reference](https://platform.deepseek.com/api-docs/) | + +### Available Models + +- **deepseek-chat**: General-purpose conversational model +- **deepseek-reasoner**: Advanced reasoning model for complex problem-solving + +## Advanced Features + +### Structured Output + +DeepSeek models support structured output through JSON mode: + +```python +from pydantic import BaseModel, Field +from strands import Agent +from strands.models.deepseek import DeepSeekModel + +class PersonInfo(BaseModel): + """Extract person information from text.""" + name: str = Field(description="Full name of the person") + age: int = Field(description="Age in years") + occupation: str = Field(description="Job or profession") + +model = DeepSeekModel( + api_key="", + model_id="deepseek-chat", +) + +agent = Agent(model=model) + +result = agent.structured_output( + PersonInfo, + "John Smith is a 30-year-old software engineer working at a tech startup." +) + +print(f"Name: {result.name}") # "John Smith" +print(f"Age: {result.age}") # 30 +print(f"Job: {result.occupation}") # "software engineer" +``` + +### Reasoning Content + +When using the reasoning model, you can access both the reasoning process and the final answer: + +```python +reasoning_model = DeepSeekModel( + api_key="", + model_id="deepseek-reasoner", +) + +agent = Agent(model=reasoning_model) + +# The model will show its reasoning process +response = agent("A farmer has 17 sheep. All but 9 die. How many are left?") +# Response will include reasoning steps and final answer +``` + +## Troubleshooting + +### Module Not Found + +If you encounter the error `ModuleNotFoundError: No module named 'openai'`, this means you haven't installed the required dependencies. DeepSeek uses OpenAI-compatible APIs, so run: + +```bash +pip install 'strands-agents[deepseek]' +``` + +### API Key Issues + +Make sure your DeepSeek API key is valid and has sufficient credits. You can obtain an API key from the [DeepSeek Platform](https://platform.deepseek.com/). + +### Rate Limiting + +DeepSeek has rate limits on API calls. If you encounter rate limiting errors, consider: +- Adding delays between requests +- Using exponential backoff +- Upgrading your API plan + +## References + +- [API](../../../api-reference/models.md) +- [DeepSeek Platform](https://platform.deepseek.com/) +- [DeepSeek API Documentation](https://platform.deepseek.com/api-docs/) \ No newline at end of file diff --git a/docs/user-guide/quickstart.md b/docs/user-guide/quickstart.md index 5a8dde79..16324f2d 100644 --- a/docs/user-guide/quickstart.md +++ b/docs/user-guide/quickstart.md @@ -227,6 +227,7 @@ More details in the [Amazon Bedrock Model Provider](concepts/model-providers/ama Strands Agents supports several other model providers beyond Amazon Bedrock: - **[Anthropic](concepts/model-providers/anthropic.md)** - Direct API access to Claude models +- **[DeepSeek](concepts/model-providers/deepseek.md)** - Access to DeepSeek's chat and reasoning models - **[LiteLLM](concepts/model-providers/litellm.md)** - Unified interface for OpenAI, Mistral, and other providers - **[Llama API](concepts/model-providers/llamaapi.md)** - Access to Meta's Llama models - **[Ollama](concepts/model-providers/ollama.md)** - Run models locally for privacy or offline use diff --git a/mkdocs.yml b/mkdocs.yml index 380c47e9..a9610659 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -85,6 +85,7 @@ nav: - Model Providers: - Amazon Bedrock: user-guide/concepts/model-providers/amazon-bedrock.md - Anthropic: user-guide/concepts/model-providers/anthropic.md + - DeepSeek: user-guide/concepts/model-providers/deepseek.md - LiteLLM: user-guide/concepts/model-providers/litellm.md - LlamaAPI: user-guide/concepts/model-providers/llamaapi.md - MistralAI: user-guide/concepts/model-providers/mistral.md @@ -127,6 +128,8 @@ nav: - Agents Workflows: examples/python/agents_workflows.md - Knowledge-Base Workflow: examples/python/knowledge_base_agent.md - Structured Output: examples/python/structured_output.md + - DeepSeek Reasoning Agent: examples/python/deepseek_reasoning_agent.md + - DeepSeek Code Completion: examples/python/deepseek_code_completion.md - Multi Agents: examples/python/multi_agent_example/multi_agent_example.md - Meta Tooling: examples/python/meta_tooling.md - MCP: examples/python/mcp_calculator.md From f0b743970a5a34a5078eb9cf90ecc39a8fc93468 Mon Sep 17 00:00:00 2001 From: Suresh Veeragoni Date: Fri, 11 Jul 2025 19:11:52 -0700 Subject: [PATCH 2/3] updates to markdown documentation formatting --- docs/examples/python/deepseek_code_completion.md | 14 +++----------- docs/examples/python/deepseek_reasoning_agent.md | 2 +- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/examples/python/deepseek_code_completion.md b/docs/examples/python/deepseek_code_completion.md index 320053bb..5051ce7e 100644 --- a/docs/examples/python/deepseek_code_completion.md +++ b/docs/examples/python/deepseek_code_completion.md @@ -40,9 +40,7 @@ Complete this Python function: def calculate_compound_interest(principal, rate, time, compound_frequency): '''Calculate compound interest.''' # TODO: Implement the compound interest formula - pass -``` -""" + pass""" ``` ### 2. Class Method Implementation @@ -67,8 +65,7 @@ class BankAccount: # TODO: Implement withdraw method with overdraft protection pass ``` -""" -``` + ### 3. Algorithm Implementation @@ -90,8 +87,7 @@ class BinarySearchTree: def search(self, val): # TODO: Search for a value in the BST pass -``` -""" + ``` ### 4. Code Refactoring @@ -111,8 +107,6 @@ def process_data(data): ``` Improve by making it more Pythonic and performant. -""" -``` ### 5. API Integration @@ -131,8 +125,6 @@ class WeatherAPIClient: # TODO: Implement method to get current weather pass ``` -""" -``` ## Complete Example Code diff --git a/docs/examples/python/deepseek_reasoning_agent.md b/docs/examples/python/deepseek_reasoning_agent.md index 4fe878bf..5346647f 100644 --- a/docs/examples/python/deepseek_reasoning_agent.md +++ b/docs/examples/python/deepseek_reasoning_agent.md @@ -83,7 +83,7 @@ Fill in the implementation for the fibonacci_sequence function. """ response = agent(fim_prompt) -``` + ### 4. Structured Reasoning Output From 91a65acd62688a2761a6c947b730967a4b0c0135 Mon Sep 17 00:00:00 2001 From: Suresh Veeragoni Date: Sat, 12 Jul 2025 02:17:44 -0700 Subject: [PATCH 3/3] FIM beta update --- docs/examples/python/deepseek_reasoning_agent.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/examples/python/deepseek_reasoning_agent.py b/docs/examples/python/deepseek_reasoning_agent.py index 9ab9084c..45644e9f 100644 --- a/docs/examples/python/deepseek_reasoning_agent.py +++ b/docs/examples/python/deepseek_reasoning_agent.py @@ -71,7 +71,8 @@ def code_completion_example(): params={ "max_tokens": 500, "temperature": 0.2, # Lower temperature for more consistent code - } + }, + use_beta=True ) agent = Agent(model=model)