(Go: >> BACK << -|- >> HOME <<)

SlideShare a Scribd company logo
Prompt engineering for iOS developers
How LLMs work
Generative AI as a service
Prompt engineering patterns
Pair programming with AI tools
How LLMs work
Generative Pre-trained Transformer
How LLMs work - GPT architecture
Input processing
Input
Output
Decoder
Contextual and Session Handling
Safety and Content Filters
Bootstrap prompts
How LLMs work - Tokenisation
Swift is a powerful and intuitive programming language for all Apple platforms.
Swift is a powerful and intuitive programming language for all Apple platforms.
How LLMs work - Token Embeddings
-0.05,
0.017
…
-0.01
Vectors with 12288 dimensions (features) and positional encoding
-0.03,
0.118
…
-0.02
-0.01,
0.007
…
-0.004
…
Swift is a powerful and intuitive programming language for all Apple platforms.
How LLMs work - Token Embeddings
This vector encapsulates the semantic meaning of Google, without the
semantics of the word Kotlin, and also includes the semantics of the
word Swift.
Google - Kotlin + Swift = ?
How LLMs work - Token Embeddings
Google - Kotlin + Swift = Apple
How LLMs work - Token Embeddings
apple, 0.426
spotify, 0.396
amazon, 0.393
net
fl
ix, 0.387
yahoo, 0.382
snapchat, 0.371
huawei, 0.368
Google - Kotlin + Swift =
How LLMs work - GPT architecture
Input processing
Transformer layer
Transformer layer
Transformer layer
120 layers (GPT4)
Next word prediction
Decoder
Input
Output
Input +
next word
Generative AI as a service - OpenAI API
Generative AI as a service - OpenAI API
{
"model": "gpt-3.5-turbo",
"messages": [{
"role": "user",
"content": "Describe Turin in one sentence"
}],
"temperature": 0.7
}
POST https://api.openai.com/v1/chat/completions
Generative AI as a service - OpenAI API
struct AIMessage: Codable {
let role: String
let prompt: String
}
struct AIRequest: Codable {
let model: String
let messages: [AIMessage]
let temperature: Double
}
extension AIRequest {
static func gpt3_5Turbo(prompt: String)
-
>
AIRequest {
.init(model: "gpt-3.5-turbo",
messages: [
.init(role: "user", prompt: prompt)
],
temperature: 0.7
)
}
}
Generative AI as a service - OpenAI API
}
@MainActor
func invoke(prompt: String) async throws
-
>
String {
Generative AI as a service - OpenAI API
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpURLResponse = (response as? HTTPURLResponse) else {
throw AIServiceError.badResponse
}
guard 200
.
.
.
399 ~= httpURLResponse.statusCode else {
throw AIServiceError.httpError(
code: httpURLResponse.statusCode,
description: String(data: data, encoding: .utf8)
?
?
""
)
}
let aiResponse = try decoder.decode(AIResponse.self, from: data)
return aiResponse.choices.f
i
rst
?
.
message.content
?
?
""
}
let openAIURL = URL(string: "https:
/
/
api.openai.com/v1/chat/completions")!
var request = URLRequest(url: openAIURL)
for (f
i
eld, value) in conf
i
g {
request.setValue(value, forHTTPHeaderField: f
i
eld)
}
request.httpMethod = "POST"
request.httpBody = try encoder.encode(AIRequest.gpt3_5Turbo(prompt: prompt))
@MainActor
func invoke(prompt: String) async throws
-
>
String {
Generative AI as a service work - OpenAI API
Generative AI as a service work - OpenAI API pricing
Model Input Output
gpt-3.5-turbo $1.50 / 1M tokens $2.00 / 1M tokens
gpt-4 $30.00 / 1M tokens $60.00 / 1M tokens
gpt-4-32k $60.00 / 1M tokens $120.00 / 1M tokens
Generative AI as a service - Amazon Bedrock
Generative AI as a service - Amazon Bedrock
Generative AI as a service work - Amazon Bedrock
Model Input Output
Titan Text Lite $0.30 / 1M tokens $0.40 / 1M tokens
Claude 3 Haiku $0.25 / 1M tokens $0.15 / 1M tokens
Titan Image
Generator
$0.005 / per image
Generative AI as a service work - Amazon Bedrock
AWS
API Gateway
Lambda
Bedrock
iOS app
Generative AI as a service work - Amazon Bedrock
def invoke_model(prompt: str)
:
try:
enclosed_prompt = "Human: " + prompt + "nnAssistant:"
body = {
"prompt": enclosed_prompt,
"max_tokens_to_sample": 500,
"temperature": 0.5,
"stop_sequences": ["nnHuman:"],
}
bedrock_runtime_client = boto3.client('bedrock
-
runtime')
response = bedrock_runtime_client.invoke_model(
modelId = "anthropic.claude
-
v2", body = json.dumps(body)
)
response_body = json.loads(response["body"].read())
completion = response_body["completion"]
return completion
except Exception as e:
raise e
Generative AI as a service work - Amazon Bedrock
def lambda_handler(event, context)
:
body = json.loads(event["body"])
prompt = body["content"]
if (event["headers"]["authorization"]
!
=
key)
:
return {
'statusCode': 401
}
try:
completion = invoke_model(prompt = prompt)
return {
'statusCode': 200,
'body': json.dumps({"content": completion})
}
except Exception as e:
return {
'statusCode': 400,
'body': json.dumps(str(e))
}
Generative AI as a service work - Amazon Bedrock
POST https://[uuid]...amazonaws.com/dev/completions
{
"content": "Describe Turin in one sentence"
}
Generative AI as a service work - Amazon Bedrock
def schedule_prompt_template(content: str)
-
>
str:
return f"""
<context>
.
.
.
/
/
Swift Heroes 2024 schedule
.
.
.
.
.
.
<
/
context>
Task for Assistent:
Find the most relevant answer in the context
<question>
{content}
<
/
question>
"""
Generative AI as a service work - Amazon Bedrock
def lambda_handler(event, context)
:
…
try:
templatedPrompt = prompt
if template
=
=
"schedule":
templatedPrompt = schedule_prompt_template(content = prompt)
elif template
=
=
"chat":
templatedPrompt = chat_context_template(content = prompt)
completion = invoke_claude(prompt = templatedPrompt)
return {
'statusCode': 200,
'body': json.dumps({"content": completion})
}
except Exception as e:
…
Generative AI as a service work - Amazon Bedrock
POST https://[uuid]...amazonaws.com/dev/completions
{
"content": "Describe Turin in one sentence”,
"template": “schedule"
}
Generative AI as a service work - Amazon Bedrock
@MainActor
func invokeBedrock(content: String, template: AITemplate = .schedule) async throws
-
>
String {
…
request.httpBody = try encoder.encode(BedrockAIRequest(content: content,
template: template.rawValue))
…
let bedrockResponse = try decoder.decode(BedrockAIResponse.self, from: data)
return bedrockResponse.content
}
let answer = try await aiService.invokeBedrock(content: text, template: .schedule)
struct BedrockAIRequest: Codable {
let content: String
let template: String
}
enum AITemplate: String {
case schedule, chat
}
Generative AI as a service work - Amazon Bedrock
Generative AI as a service work - Amazon Bedrock
Prompt engineering
The emerging skill set focused on designing and optimizing inputs for AI
systems to ensure they generate optimal outputs.
Prompt engineering patterns
One-shot, Few-shot and Zero-shot prompts
Summarize all the talks between context tags
Provide output as an array of json objects with a title, one main topic, and an array of tags.
The tags should not repeat the main topic.
<example>
Title: "Inclusive design: crafting Accessible apps for all of us"
Abstract: "One of the main goals for an app developer should be to reach everyone. ...
<result>
{{
"title": "Inclusive design: crafting Accessible apps for all of us"
"topic": "Accessibility"
"tags": ["user experience", "design", "assistance", "tools", "SwiftUI", "Swift", "Apple"]
}}
</result>
<context>
// Swift Heroes 2024 schedule …
</context>
</example>
Prompt engineering patterns
[
{
"title": "Building Swift CLIs that your users and contributors love",
"topic": "Swift CLIs",
"tags": ["terminal", "Tuist", "contributors"]
},
{
"title": "Macro Polo: A new generation of code generation",
"topic": "Swift Macros",
"tags": ["code generation", "modules", "examples"]
},
{
"title": "Typestate - the new Design Pattern in Swift 5.9",
"topic": "Typestate Design Pattern",
"tags": ["state machines", "memory ownership", "generics", "constraints", "safety"]
},
{
"title": "A Tale of Modular Architecture with SPM",
"topic": "Modular Architecture",
"tags": ["MVVM", "SwiftUI", "SPM"]
},
.
.
.
]
Prompt engineering patterns
Persona and audience
How does async/await work in Swift?
Act as an Experienced iOS developer
Explain to 12 years old
Prompt engineering patterns
Chain-of-thought
How does async/await work in Swift?
Act as an Experienced iOS developer
Explain to the Product manager
Follow this Chain-of-thought:
- Technical details using understandable to the audience analogy
- Bene
fi
ts relevant for the audience
- Additional things to consider
Pair programming with AI tools - Copilot
Pair programming with AI tools - Copilot
Pair programming with AI tools - Copilot
Pair programming with AI tools - Copilot Chat
Pair programming with AI tools - ChatGPT
Discovering Swift Packages
Converting from legacy code
Writing unit tests and generating test data
Multiplatform development
Brainstorming and evaluating ideas
Future
Thank you
@blob8129

More Related Content

Similar to Prompt engineering for iOS developers (How LLMs and GenAI work)

Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
Daniel Spector
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
Maarten Balliauw
 
mobl
moblmobl
mobl
zefhemel
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP Developers
Jeremy Lindblom
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
gturnquist
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
Erick Ranes Akbar Mawuntu
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
Siarzh Miadzvedzeu
 
Symfony + GraphQL
Symfony + GraphQLSymfony + GraphQL
Symfony + GraphQL
Alex Demchenko
 
Graphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiDGraphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiD
CODEiD PHP Community
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
Dmitriy Sobko
 
Scala & sling
Scala & slingScala & sling
Scala & sling
michid
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
Shumpei Shiraishi
 
Using Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineUsing Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App Engine
River of Talent
 
A Blueprint for Scala Microservices
A Blueprint for Scala MicroservicesA Blueprint for Scala Microservices
A Blueprint for Scala Microservices
Federico Feroldi
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
Ramon Ribeiro Rabello
 
PHP-Part3
PHP-Part3PHP-Part3
PHP-Part3
Ahmed Saihood
 
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverAltitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Fastly
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 

Similar to Prompt engineering for iOS developers (How LLMs and GenAI work) (20)

Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
mobl
moblmobl
mobl
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP Developers
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Integrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat applicationIntegrating dialog flow (api.ai) into qiscus sdk chat application
Integrating dialog flow (api.ai) into qiscus sdk chat application
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Symfony + GraphQL
Symfony + GraphQLSymfony + GraphQL
Symfony + GraphQL
 
Graphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiDGraphql + Symfony | Александр Демченко | CODEiD
Graphql + Symfony | Александр Демченко | CODEiD
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
 
Scala & sling
Scala & slingScala & sling
Scala & sling
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Using Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineUsing Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App Engine
 
A Blueprint for Scala Microservices
A Blueprint for Scala MicroservicesA Blueprint for Scala Microservices
A Blueprint for Scala Microservices
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
PHP-Part3
PHP-Part3PHP-Part3
PHP-Part3
 
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverAltitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 

More from Andrey Volobuev

Protocols and generics in Swift
Protocols and generics in SwiftProtocols and generics in Swift
Protocols and generics in Swift
Andrey Volobuev
 
State machines in iOS
State machines in iOSState machines in iOS
State machines in iOS
Andrey Volobuev
 
ML
MLML
Mobile architectures
Mobile architecturesMobile architectures
Mobile architectures
Andrey Volobuev
 
Functional
FunctionalFunctional
Functional
Andrey Volobuev
 
How React works
How React works How React works
How React works
Andrey Volobuev
 
Unit testing iOS Applications
Unit testing iOS ApplicationsUnit testing iOS Applications
Unit testing iOS Applications
Andrey Volobuev
 
Архитектура компилятора Swift
Архитектура компилятора SwiftАрхитектура компилятора Swift
Архитектура компилятора Swift
Andrey Volobuev
 
Преимущества и недостатки языка Swift
Преимущества и недостатки языка SwiftПреимущества и недостатки языка Swift
Преимущества и недостатки языка Swift
Andrey Volobuev
 

More from Andrey Volobuev (9)

Protocols and generics in Swift
Protocols and generics in SwiftProtocols and generics in Swift
Protocols and generics in Swift
 
State machines in iOS
State machines in iOSState machines in iOS
State machines in iOS
 
ML
MLML
ML
 
Mobile architectures
Mobile architecturesMobile architectures
Mobile architectures
 
Functional
FunctionalFunctional
Functional
 
How React works
How React works How React works
How React works
 
Unit testing iOS Applications
Unit testing iOS ApplicationsUnit testing iOS Applications
Unit testing iOS Applications
 
Архитектура компилятора Swift
Архитектура компилятора SwiftАрхитектура компилятора Swift
Архитектура компилятора Swift
 
Преимущества и недостатки языка Swift
Преимущества и недостатки языка SwiftПреимущества и недостатки языка Swift
Преимущества и недостатки языка Swift
 

Recently uploaded

Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)
andrehoraa
 
Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...
Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...
Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...
3610stuck
 
Authentication Review-June -2024 AP & TS.pptx
Authentication Review-June -2024 AP & TS.pptxAuthentication Review-June -2024 AP & TS.pptx
Authentication Review-June -2024 AP & TS.pptx
DEMONDUOS
 
🚂🚘 Premium Girls Call Ranchi 🛵🚡000XX00000 💃 Choose Best And Top Girl Service...
🚂🚘 Premium Girls Call Ranchi  🛵🚡000XX00000 💃 Choose Best And Top Girl Service...🚂🚘 Premium Girls Call Ranchi  🛵🚡000XX00000 💃 Choose Best And Top Girl Service...
🚂🚘 Premium Girls Call Ranchi 🛵🚡000XX00000 💃 Choose Best And Top Girl Service...
bahubalikumar09988
 
01. Ruby Introduction - Ruby Core Teaching
01. Ruby Introduction - Ruby Core Teaching01. Ruby Introduction - Ruby Core Teaching
01. Ruby Introduction - Ruby Core Teaching
quanhoangd129
 
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
shanihomely
 
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
John Gallagher
 
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
Shane Coughlan
 
GT degree offer diploma Transcript
GT degree offer diploma TranscriptGT degree offer diploma Transcript
GT degree offer diploma Transcript
attueb
 
08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching
quanhoangd129
 
03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching
quanhoangd129
 
Fantastic Design Patterns and Where to use them No Notes.pdf
Fantastic Design Patterns and Where to use them No Notes.pdfFantastic Design Patterns and Where to use them No Notes.pdf
Fantastic Design Patterns and Where to use them No Notes.pdf
6m9p7qnjj8
 
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdfA Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
kalichargn70th171
 
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Deliverybangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Empowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - GrawlixEmpowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - Grawlix
Aarisha Shaikh
 
SEO Cheat Sheet with Learning Resources by Balti Bloggers.pdf
SEO Cheat Sheet with Learning Resources by Balti Bloggers.pdfSEO Cheat Sheet with Learning Resources by Balti Bloggers.pdf
SEO Cheat Sheet with Learning Resources by Balti Bloggers.pdf
Balti Bloggers
 
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
902basic
 
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdfAI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
Daniel Zivkovic
 
06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching
quanhoangd129
 
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDSAmadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
aadhiyaeliza
 

Recently uploaded (20)

Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)
 
Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...
Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...
Mumbai Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service A...
 
Authentication Review-June -2024 AP & TS.pptx
Authentication Review-June -2024 AP & TS.pptxAuthentication Review-June -2024 AP & TS.pptx
Authentication Review-June -2024 AP & TS.pptx
 
🚂🚘 Premium Girls Call Ranchi 🛵🚡000XX00000 💃 Choose Best And Top Girl Service...
🚂🚘 Premium Girls Call Ranchi  🛵🚡000XX00000 💃 Choose Best And Top Girl Service...🚂🚘 Premium Girls Call Ranchi  🛵🚡000XX00000 💃 Choose Best And Top Girl Service...
🚂🚘 Premium Girls Call Ranchi 🛵🚡000XX00000 💃 Choose Best And Top Girl Service...
 
01. Ruby Introduction - Ruby Core Teaching
01. Ruby Introduction - Ruby Core Teaching01. Ruby Introduction - Ruby Core Teaching
01. Ruby Introduction - Ruby Core Teaching
 
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
Russian Girls Call Mumbai 🎈🔥9930687706 🔥💋🎈 Provide Best And Top Girl Service ...
 
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
 
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
 
GT degree offer diploma Transcript
GT degree offer diploma TranscriptGT degree offer diploma Transcript
GT degree offer diploma Transcript
 
08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching
 
03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching
 
Fantastic Design Patterns and Where to use them No Notes.pdf
Fantastic Design Patterns and Where to use them No Notes.pdfFantastic Design Patterns and Where to use them No Notes.pdf
Fantastic Design Patterns and Where to use them No Notes.pdf
 
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdfA Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
 
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Deliverybangalore Girls call  👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
bangalore Girls call 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Empowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - GrawlixEmpowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - Grawlix
 
SEO Cheat Sheet with Learning Resources by Balti Bloggers.pdf
SEO Cheat Sheet with Learning Resources by Balti Bloggers.pdfSEO Cheat Sheet with Learning Resources by Balti Bloggers.pdf
SEO Cheat Sheet with Learning Resources by Balti Bloggers.pdf
 
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
 
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdfAI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
 
06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching
 
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDSAmadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
 

Prompt engineering for iOS developers (How LLMs and GenAI work)

  • 1. Prompt engineering for iOS developers
  • 2. How LLMs work Generative AI as a service Prompt engineering patterns Pair programming with AI tools
  • 3. How LLMs work Generative Pre-trained Transformer
  • 4. How LLMs work - GPT architecture Input processing Input Output Decoder Contextual and Session Handling Safety and Content Filters Bootstrap prompts
  • 5. How LLMs work - Tokenisation Swift is a powerful and intuitive programming language for all Apple platforms. Swift is a powerful and intuitive programming language for all Apple platforms.
  • 6. How LLMs work - Token Embeddings -0.05, 0.017 … -0.01 Vectors with 12288 dimensions (features) and positional encoding -0.03, 0.118 … -0.02 -0.01, 0.007 … -0.004 … Swift is a powerful and intuitive programming language for all Apple platforms.
  • 7. How LLMs work - Token Embeddings This vector encapsulates the semantic meaning of Google, without the semantics of the word Kotlin, and also includes the semantics of the word Swift. Google - Kotlin + Swift = ?
  • 8. How LLMs work - Token Embeddings Google - Kotlin + Swift = Apple
  • 9. How LLMs work - Token Embeddings apple, 0.426 spotify, 0.396 amazon, 0.393 net fl ix, 0.387 yahoo, 0.382 snapchat, 0.371 huawei, 0.368 Google - Kotlin + Swift =
  • 10. How LLMs work - GPT architecture Input processing Transformer layer Transformer layer Transformer layer 120 layers (GPT4) Next word prediction Decoder Input Output Input + next word
  • 11. Generative AI as a service - OpenAI API
  • 12. Generative AI as a service - OpenAI API { "model": "gpt-3.5-turbo", "messages": [{ "role": "user", "content": "Describe Turin in one sentence" }], "temperature": 0.7 } POST https://api.openai.com/v1/chat/completions
  • 13. Generative AI as a service - OpenAI API struct AIMessage: Codable { let role: String let prompt: String } struct AIRequest: Codable { let model: String let messages: [AIMessage] let temperature: Double } extension AIRequest { static func gpt3_5Turbo(prompt: String) - > AIRequest { .init(model: "gpt-3.5-turbo", messages: [ .init(role: "user", prompt: prompt) ], temperature: 0.7 ) } }
  • 14. Generative AI as a service - OpenAI API } @MainActor func invoke(prompt: String) async throws - > String {
  • 15. Generative AI as a service - OpenAI API let (data, response) = try await URLSession.shared.data(for: request) guard let httpURLResponse = (response as? HTTPURLResponse) else { throw AIServiceError.badResponse } guard 200 . . . 399 ~= httpURLResponse.statusCode else { throw AIServiceError.httpError( code: httpURLResponse.statusCode, description: String(data: data, encoding: .utf8) ? ? "" ) } let aiResponse = try decoder.decode(AIResponse.self, from: data) return aiResponse.choices.f i rst ? . message.content ? ? "" } let openAIURL = URL(string: "https: / / api.openai.com/v1/chat/completions")! var request = URLRequest(url: openAIURL) for (f i eld, value) in conf i g { request.setValue(value, forHTTPHeaderField: f i eld) } request.httpMethod = "POST" request.httpBody = try encoder.encode(AIRequest.gpt3_5Turbo(prompt: prompt)) @MainActor func invoke(prompt: String) async throws - > String {
  • 16. Generative AI as a service work - OpenAI API
  • 17. Generative AI as a service work - OpenAI API pricing Model Input Output gpt-3.5-turbo $1.50 / 1M tokens $2.00 / 1M tokens gpt-4 $30.00 / 1M tokens $60.00 / 1M tokens gpt-4-32k $60.00 / 1M tokens $120.00 / 1M tokens
  • 18. Generative AI as a service - Amazon Bedrock
  • 19. Generative AI as a service - Amazon Bedrock
  • 20. Generative AI as a service work - Amazon Bedrock Model Input Output Titan Text Lite $0.30 / 1M tokens $0.40 / 1M tokens Claude 3 Haiku $0.25 / 1M tokens $0.15 / 1M tokens Titan Image Generator $0.005 / per image
  • 21. Generative AI as a service work - Amazon Bedrock AWS API Gateway Lambda Bedrock iOS app
  • 22. Generative AI as a service work - Amazon Bedrock def invoke_model(prompt: str) : try: enclosed_prompt = "Human: " + prompt + "nnAssistant:" body = { "prompt": enclosed_prompt, "max_tokens_to_sample": 500, "temperature": 0.5, "stop_sequences": ["nnHuman:"], } bedrock_runtime_client = boto3.client('bedrock - runtime') response = bedrock_runtime_client.invoke_model( modelId = "anthropic.claude - v2", body = json.dumps(body) ) response_body = json.loads(response["body"].read()) completion = response_body["completion"] return completion except Exception as e: raise e
  • 23. Generative AI as a service work - Amazon Bedrock def lambda_handler(event, context) : body = json.loads(event["body"]) prompt = body["content"] if (event["headers"]["authorization"] ! = key) : return { 'statusCode': 401 } try: completion = invoke_model(prompt = prompt) return { 'statusCode': 200, 'body': json.dumps({"content": completion}) } except Exception as e: return { 'statusCode': 400, 'body': json.dumps(str(e)) }
  • 24. Generative AI as a service work - Amazon Bedrock POST https://[uuid]...amazonaws.com/dev/completions { "content": "Describe Turin in one sentence" }
  • 25. Generative AI as a service work - Amazon Bedrock def schedule_prompt_template(content: str) - > str: return f""" <context> . . . / / Swift Heroes 2024 schedule . . . . . . < / context> Task for Assistent: Find the most relevant answer in the context <question> {content} < / question> """
  • 26. Generative AI as a service work - Amazon Bedrock def lambda_handler(event, context) : … try: templatedPrompt = prompt if template = = "schedule": templatedPrompt = schedule_prompt_template(content = prompt) elif template = = "chat": templatedPrompt = chat_context_template(content = prompt) completion = invoke_claude(prompt = templatedPrompt) return { 'statusCode': 200, 'body': json.dumps({"content": completion}) } except Exception as e: …
  • 27. Generative AI as a service work - Amazon Bedrock POST https://[uuid]...amazonaws.com/dev/completions { "content": "Describe Turin in one sentence”, "template": “schedule" }
  • 28. Generative AI as a service work - Amazon Bedrock @MainActor func invokeBedrock(content: String, template: AITemplate = .schedule) async throws - > String { … request.httpBody = try encoder.encode(BedrockAIRequest(content: content, template: template.rawValue)) … let bedrockResponse = try decoder.decode(BedrockAIResponse.self, from: data) return bedrockResponse.content } let answer = try await aiService.invokeBedrock(content: text, template: .schedule) struct BedrockAIRequest: Codable { let content: String let template: String } enum AITemplate: String { case schedule, chat }
  • 29. Generative AI as a service work - Amazon Bedrock
  • 30. Generative AI as a service work - Amazon Bedrock
  • 31. Prompt engineering The emerging skill set focused on designing and optimizing inputs for AI systems to ensure they generate optimal outputs.
  • 32. Prompt engineering patterns One-shot, Few-shot and Zero-shot prompts Summarize all the talks between context tags Provide output as an array of json objects with a title, one main topic, and an array of tags. The tags should not repeat the main topic. <example> Title: "Inclusive design: crafting Accessible apps for all of us" Abstract: "One of the main goals for an app developer should be to reach everyone. ... <result> {{ "title": "Inclusive design: crafting Accessible apps for all of us" "topic": "Accessibility" "tags": ["user experience", "design", "assistance", "tools", "SwiftUI", "Swift", "Apple"] }} </result> <context> // Swift Heroes 2024 schedule … </context> </example>
  • 33. Prompt engineering patterns [ { "title": "Building Swift CLIs that your users and contributors love", "topic": "Swift CLIs", "tags": ["terminal", "Tuist", "contributors"] }, { "title": "Macro Polo: A new generation of code generation", "topic": "Swift Macros", "tags": ["code generation", "modules", "examples"] }, { "title": "Typestate - the new Design Pattern in Swift 5.9", "topic": "Typestate Design Pattern", "tags": ["state machines", "memory ownership", "generics", "constraints", "safety"] }, { "title": "A Tale of Modular Architecture with SPM", "topic": "Modular Architecture", "tags": ["MVVM", "SwiftUI", "SPM"] }, . . . ]
  • 34. Prompt engineering patterns Persona and audience How does async/await work in Swift? Act as an Experienced iOS developer Explain to 12 years old
  • 35. Prompt engineering patterns Chain-of-thought How does async/await work in Swift? Act as an Experienced iOS developer Explain to the Product manager Follow this Chain-of-thought: - Technical details using understandable to the audience analogy - Bene fi ts relevant for the audience - Additional things to consider
  • 36. Pair programming with AI tools - Copilot
  • 37. Pair programming with AI tools - Copilot
  • 38. Pair programming with AI tools - Copilot
  • 39. Pair programming with AI tools - Copilot Chat
  • 40. Pair programming with AI tools - ChatGPT Discovering Swift Packages Converting from legacy code Writing unit tests and generating test data Multiplatform development Brainstorming and evaluating ideas